<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<meta http-equiv="cache-control" content="no-cache">
<title>Genivia - XML-RPC/JSON and jsoncpp</title>
<link href="genivia_tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="genivia_content.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="top">
 <div id="titlearea">
  <table height="72px" width="100%" cellspacing="0" cellpadding="0">
   <tbody>
    <tr>
     <td width="10%">&nbsp;</td>
     <td width="175px"><a href="https://www.genivia.com"><img alt="Genivia" src="GeniviaLogo2_trans_noslogan.png"/></a></td>
     <td class="tab_home"><a href="https://www.genivia.com">Home</a></td>
     <td class="tab_home"><a href="https://www.genivia.com/docs.html">Documentation</a></td>
     <td>
      <div style="float: right; font-size: 18px; font-weight: bold;">XML-RPC/JSON and jsoncpp</div>
      <br>
      <div style="float: right; font-size: 10px;">updated Fri Oct 16 2020 by Robert van Engelen</div>
     </td>
     <td width="10%">&nbsp;</td>
    </tr>
   </tbody>
  </table>
 </div>
<!-- Generated by Doxygen 1.8.11 -->
  <div id="navrow1" class="tabs">
    <ul class="tablist">
      <li class="current"><a href="index.html"><span>Main&#160;Page</span></a></li>
      <li><a href="annotated.html"><span>Classes</span></a></li>
      <li><a href="files.html"><span>Files</span></a></li>
    </ul>
  </div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">XML-RPC/JSON and jsoncpp </div>  </div>
</div><!--header-->
<div class="contents">
<div class="toc"><h3>Table of Contents</h3>
<ul><li class="level1"><a href="#intro">Introduction                                                            </a><ul><li class="level2"><a href="#intro-1">JSON and gSOAP                                                       </a></li>
</ul>
</li>
<li class="level1"><a href="#jsoncpp">The jsoncpp command-line tool                                         </a><ul><li class="level2"><a href="#jsoncpp-1">Building and installing jsoncpp                                     </a></li>
<li class="level2"><a href="#jsoncpp-2">Command-line options                                                </a></li>
<li class="level2"><a href="#jsoncpp-3">JSONPath syntax                                                     </a></li>
<li class="level2"><a href="#jsoncpp-4">JSONPath by example                                                 </a></li>
</ul>
</li>
<li class="level1"><a href="#cpp">C++ XML-RPC and JSON                                                      </a><ul><li class="level2"><a href="#cpp-files">List of files                                                       </a></li>
<li class="level2"><a href="#cpp-ex">Overview                                                               </a></li>
<li class="level2"><a href="#cpp-cl">C++ XML-RPC client example                                             </a></li>
<li class="level2"><a href="#cpp-sr">C++ XML-RPC server example                                             </a></li>
<li class="level2"><a href="#cpp-io">C++ XML-RPC serialization from/to streams                              </a></li>
<li class="level2"><a href="#cpp-js">C++ JSON serialization from/to streams                                 </a></li>
<li class="level2"><a href="#cpp-jr">C++ JSON REST clients and servers                                      </a></li>
<li class="level2"><a href="#cpp-rpc">C++ JSON-RPC clients and servers                                      </a></li>
<li class="level2"><a href="#cpp-raw">Embedding and serializing raw JSON data as a JSON value in C++        </a></li>
<li class="level2"><a href="#json-ns">Moving JSON types and operations into a C++ namespace                 </a></li>
</ul>
</li>
<li class="level1"><a href="#c">C XML-RPC and JSON                                                          </a><ul><li class="level2"><a href="#c-files">List of files                                                         </a></li>
<li class="level2"><a href="#c-ex">Overview                                                                 </a></li>
<li class="level2"><a href="#c-cl">C XML-RPC client example                                                 </a></li>
<li class="level2"><a href="#c-js">C JSON serialization                                                     </a></li>
<li class="level2"><a href="#c-jr">C JSON REST clients and servers                                          </a></li>
<li class="level2"><a href="#c-rpc">C JSON-RPC clients and servers                                          </a></li>
<li class="level2"><a href="#c-raw">Embedding and serializing raw JSON data as a JSON value in C            </a></li>
</ul>
</li>
<li class="level1"><a href="#misc">Miscellaneous                                                            </a><ul><li class="level2"><a href="#json-cc">Compiling XML-RPC/JSON together with gSOAP SOAP services and XML      </a></li>
<li class="level2"><a href="#soap">Serving JSON and SOAP requests on the same server port                   </a></li>
<li class="level2"><a href="#fp">Floating point format                                                      </a></li>
<li class="level2"><a href="#base64">JSON and base64                                                        </a></li>
<li class="level2"><a href="#dateTime">JSON and ISO 8601 dateTime                                           </a></li>
<li class="level2"><a href="#issues">Potential issues                                                       </a></li>
</ul>
</li>
<li class="level1"><a href="#copyright">Copyright                                                           </a></li>
</ul>
</div>
<div class="textblock"><h1><a class="anchor" id="intro"></a>
Introduction                                                            </h1>
<p>XML-RPC predates JSON and shares the same goal to offer a simple data format for Web applications that interoperate via "remote procedure calls" (RPC) over "stateless" HTTP via HTTP POST. Applications are not limited to the exchange of RPC messages via HTTP POST. Other REST methods can be used to manage the state of resources via URL references, allowing for the storage of data (HTTP PUT), retrieval of data (HTTP GET), and removal of data (HTTP DELETE) from a resource.</p>
<p>XML-RPC is a generic, self-describing (and very verbose) XML format to compose XML messages for platform-neutral data exchange. XML-RPC defines a collection of frequently used XML types with common programming language equivalents. XML-RPC does NOT provide a data binding to XML and does NOT support a validation mechanism to ensure that data content is validated against a schema. XML-RPC serialization proceeds by marshaling parameters in predefined XML elements for each data type. XML-RPC has primitive types (bool, int, double, string, dateTime, base64) and two compound types (structs and arrays).</p>
<p>This document does not describe XML-RPC in detail. For more details, please visit <a href="http://www.xmlrpc.com">http://www.xmlrpc.com</a>.</p>
<p>JSON (JavaScript Object Notation) is an even simpler data format to support platform-neutral data interchange that is highly compatible across programming languages by restricting data representation to a set of five common types: bool, number, string, array, and object. A JSON object is the same as an XML-RPC struct. Only the syntax differs. Both are composed of fieldname-value member pairs (i.e. dictionaries or hashmaps) and have no other special properties. Which is in contrast to XML data "as objects" that are namespace scoped and may include xsi:type attributes to distinguish derived from base types, and may include id-ref attributes to cross-reference data, and other properties that make XML more suitable to achieve lossless C/C++ serialization.</p>
<p>This document does not describe JSON (and JSON RPC/REST) in detail. For more details, please visit <a href="http://www.json.org">http://www.json.org</a>.</p>
<p>This document describes both the C and C++/C++11 XML-RPC and JSON library APIs, see table of contents.</p>
<h2><a class="anchor" id="intro-1"></a>
JSON and gSOAP                                                       </h2>
<p>The gSOAP JSON API is compact and lightweight. It is straightforward to write JSON RPC and JSON REST code. For example, a JSON REST call in C++:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="keywordtype">int</span> main()</div><div class="line">{</div><div class="line">  soap *ctx = soap_new1(SOAP_C_UTFSTRING);    <span class="comment">// set up context to manage memory</span></div><div class="line">  <span class="keyword">const</span> <span class="keywordtype">char</span> *endpoint = <span class="stringliteral">&quot;http://www.cs.fsu.edu/~engelen/currentTimeJSON.cgi&quot;</span>;</div><div class="line">  <a class="code" href="structvalue.html">value</a> req(ctx), res(ctx);                   <span class="comment">// new JSON values req and res</span></div><div class="line">  req = <span class="stringliteral">&quot;getCurrentTime&quot;</span>;                     <span class="comment">// request current time</span></div><div class="line">  <a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(ctx,                              <span class="comment">// make a call (POST)</span></div><div class="line">      endpoint,                               <span class="comment">// the service endpoint URL</span></div><div class="line">      req,                                    <span class="comment">// value with the request string</span></div><div class="line">      res)                                    <span class="comment">// response, if call is OK</span></div><div class="line">  );</div><div class="line">  <span class="keywordflow">if</span> (ctx-&gt;error)</div><div class="line">    ...                                       <span class="comment">// handle IO error or HTTP status code</span></div><div class="line">  <span class="keywordflow">else</span></div><div class="line">    cout &lt;&lt; <span class="stringliteral">&quot;Current time = &quot;</span> &lt;&lt; res &lt;&lt; endl; <span class="comment">// JSON response to cout</span></div><div class="line">}</div></div><!-- fragment --><p>For more details on JSON-RPC and JSON REST operations, see <a class="el" href="index.html#cpp-rpc">C++ JSON-RPC clients and servers </a>.</p>
<p>To compile this example see the <a class="el" href="index.html#cpp-files">List of files </a>.</p>
<p>Furthermore, to help you quickly develop C/C++ JSON code, we offer a code generator <b>jsoncpp</b> with the gSOAP package (version 2.8.26 and up). You can find the jsoncpp tool with the JSON examples in <code>gsoap/samples/xml-rpc-json</code>.</p>
<p>The jsoncpp command-line tool auto-generates C or C++ code from a JSON fragment. The generated code creates a JSON node graph for this fragment, which can be further tweaked as necessary. We demonstrate this on an example <code>menu.json</code> file, where we show each command executed in a command shell followed by the results displayed in the terminal: </p><pre class="fragment">cat menu.json
</pre><div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;menu&quot;: {</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;    &quot;id&quot;: &quot;file&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;    &quot;value&quot;: &quot;File&quot;,</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;    &quot;popup&quot;: {</div><div class="line"><a name="l00006"></a><span class="lineno">    6</span>&#160;      &quot;menuitem&quot;: [</div><div class="line"><a name="l00007"></a><span class="lineno">    7</span>&#160;        {&quot;value&quot;: &quot;New&quot;, &quot;onclick&quot;: &quot;CreateNewDoc()&quot;},</div><div class="line"><a name="l00008"></a><span class="lineno">    8</span>&#160;        {&quot;value&quot;: &quot;Open&quot;, &quot;onclick&quot;: &quot;OpenDoc()&quot;},</div><div class="line"><a name="l00009"></a><span class="lineno">    9</span>&#160;        {&quot;value&quot;: &quot;Close&quot;, &quot;onclick&quot;: &quot;CloseDoc()&quot;}</div><div class="line"><a name="l00010"></a><span class="lineno">   10</span>&#160;      ]</div><div class="line"><a name="l00011"></a><span class="lineno">   11</span>&#160;    }</div><div class="line"><a name="l00012"></a><span class="lineno">   12</span>&#160;  }</div><div class="line"><a name="l00013"></a><span class="lineno">   13</span>&#160;}</div></div><!-- fragment --> </div> <pre class="fragment">jsoncpp menu.json
</pre><div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">{ <span class="comment">// Generated by jsoncpp menu.json</span></div><div class="line">  <span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">  ctx-&gt;double_format = <span class="stringliteral">&quot;%lG&quot;</span>;</div><div class="line"></div><div class="line">  <a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;id&quot;</span>] = <span class="stringliteral">&quot;file&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;value&quot;</span>] = <span class="stringliteral">&quot;File&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][0][<span class="stringliteral">&quot;value&quot;</span>] = <span class="stringliteral">&quot;New&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][0][<span class="stringliteral">&quot;onclick&quot;</span>] = <span class="stringliteral">&quot;CreateNewDoc()&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][1][<span class="stringliteral">&quot;value&quot;</span>] = <span class="stringliteral">&quot;Open&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][1][<span class="stringliteral">&quot;onclick&quot;</span>] = <span class="stringliteral">&quot;OpenDoc()&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][2][<span class="stringliteral">&quot;value&quot;</span>] = <span class="stringliteral">&quot;Close&quot;</span>;</div><div class="line">  x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][2][<span class="stringliteral">&quot;onclick&quot;</span>] = <span class="stringliteral">&quot;CloseDoc()&quot;</span>;</div><div class="line">  std::cout &lt;&lt; x &lt;&lt; std::endl;</div><div class="line"></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>You can use jsoncpp option <code>-e</code> to add explanatory comments to the generated code, which explains what the code does to help you understand the JSON API.</p>
<p>Use jsoncpp option <code>-M</code> to narrow the generated code down to the essentials, without the initialization and cleanup parts of the code. This makes the generated code suitable for direct inclusion in your codebase.</p>
<p>Generating code to populate a node graph is one option. Another option is to generate code to inspect a node graph. Use jsoncpp option <code>-i</code> (gSOAP 2.8.28 and up) to generate code to inspect the node graph of a value parsed from JSON input, given that the JSON file provided with option <code>-i</code> serves as a generic template: </p><pre class="fragment">jsoncpp -i menu.json
</pre><div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">{ <span class="comment">// Generated by jsoncpp -i menu.json</span></div><div class="line">  <span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">  ctx-&gt;double_format = <span class="stringliteral">&quot;%lG&quot;</span>;</div><div class="line"></div><div class="line">  <a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">  std::cin &gt;&gt; x;</div><div class="line">  <span class="keywordflow">if</span> (x.soap-&gt;error)</div><div class="line">    exit(EXIT_FAILURE); <span class="comment">// error parsing JSON</span></div><div class="line"><span class="preprocessor">  #define USE_VAL(path, val) std::cout &lt;&lt; path &lt;&lt; &quot; = &quot; &lt;&lt; val &lt;&lt; std::endl</span></div><div class="line">  <span class="keywordflow">if</span> (x.has(<span class="stringliteral">&quot;menu&quot;</span>))</div><div class="line">  {</div><div class="line">    <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>].has(<span class="stringliteral">&quot;id&quot;</span>))</div><div class="line">      USE_VAL(<span class="stringliteral">&quot;$.menu.id&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;id&quot;</span>]);</div><div class="line">    <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>].has(<span class="stringliteral">&quot;value&quot;</span>))</div><div class="line">      USE_VAL(<span class="stringliteral">&quot;$.menu.value&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;value&quot;</span>]);</div><div class="line">    <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>].has(<span class="stringliteral">&quot;popup&quot;</span>))</div><div class="line">    {</div><div class="line">      <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>].has(<span class="stringliteral">&quot;menuitem&quot;</span>))</div><div class="line">      {</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i3 = 0; i3 &lt; x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>].size(); i3++)</div><div class="line">        {</div><div class="line">          <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i3].has(<span class="stringliteral">&quot;value&quot;</span>))</div><div class="line">            USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].value&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i3][<span class="stringliteral">&quot;value&quot;</span>]);</div><div class="line">          <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i3].has(<span class="stringliteral">&quot;onclick&quot;</span>))</div><div class="line">            USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].onclick&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i3][<span class="stringliteral">&quot;onclick&quot;</span>]);</div><div class="line">        }</div><div class="line">      }</div><div class="line">    }</div><div class="line">  }</div><div class="line">  std::cout &lt;&lt; x &lt;&lt; std::endl;</div><div class="line"></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>As you notice, each access to deeper JSON values in objects is guarded by a check that the object property is present. This helps to identify missing data in the JSON data received, but this checking is not strictly necessary to access values. When a non-existent obect property is accessed, its value returned is <code>null</code>. For example, you can access <code>x["menu"]["id"]</code> directly to obtain the <code>id</code> value, even when <code>menu</code> is not an object because this will cast <code>menu</code> into an object (i.e. internally changing the JSON graph without triggering exceptions or errors): </p><pre class="fragment">jsoncpp -k menu.json
</pre><div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">{ <span class="comment">// Generated by jsoncpp -k menu.json</span></div><div class="line">  <span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">  ctx-&gt;double_format = <span class="stringliteral">&quot;%lG&quot;</span>;</div><div class="line"></div><div class="line">  <a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">  std::cin &gt;&gt; x;</div><div class="line">  <span class="keywordflow">if</span> (x.soap-&gt;error)</div><div class="line">    exit(EXIT_FAILURE); <span class="comment">// error parsing JSON</span></div><div class="line"><span class="preprocessor">  #define USE_VAL(path, val) std::cout &lt;&lt; path &lt;&lt; &quot; = &quot; &lt;&lt; val &lt;&lt; std::endl</span></div><div class="line">  USE_VAL(<span class="stringliteral">&quot;$.menu.id&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;id&quot;</span>]);</div><div class="line">  USE_VAL(<span class="stringliteral">&quot;$.menu.value&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;value&quot;</span>]);</div><div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i0 = 0; i0 &lt; x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>].size(); i0++)</div><div class="line">  {</div><div class="line">    USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].value&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i0][<span class="stringliteral">&quot;value&quot;</span>]);</div><div class="line">    USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].onclick&quot;</span>, x[<span class="stringliteral">&quot;menu&quot;</span>][<span class="stringliteral">&quot;popup&quot;</span>][<span class="stringliteral">&quot;menuitem&quot;</span>][i0][<span class="stringliteral">&quot;onclick&quot;</span>]);</div><div class="line">  }</div><div class="line">  std::cout &lt;&lt; x &lt;&lt; std::endl;</div><div class="line"></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>On the other hand, checking for the presence of data before accessing it preserves its original structure, which may be important with respect to the type of application that uses JSON.</p>
<p>The two examples above display the JSON values with the macro <code>USE_VAL</code>, which takes a JSON <code>val</code> of type <code>value</code>.</p>
<p>Furthermore, we can assign the JSON values to auto-generated local variables using option <code>-l</code> with options <code>-i</code> or <code>-k</code>: </p><pre class="fragment">jsoncpp -k -l menu.json
</pre><div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">{ <span class="comment">// Generated by jsoncpp -k -l menu.json</span></div><div class="line">  <span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">  ctx-&gt;double_format = <span class="stringliteral">&quot;%lG&quot;</span>;</div><div class="line"></div><div class="line">  <a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">  std::cin &gt;&gt; x;</div><div class="line">  <span class="keywordflow">if</span> (x.soap-&gt;error)</div><div class="line">    exit(EXIT_FAILURE); <span class="comment">// error parsing JSON</span></div><div class="line"><span class="preprocessor">  #define USE_VAL(path, val) std::cout &lt;&lt; path &lt;&lt; &quot; = &quot; &lt;&lt; val &lt;&lt; std::endl</span></div><div class="line">  <a class="code" href="structvalue.html">value</a>&amp; x_menu = x[<span class="stringliteral">&quot;menu&quot;</span>];</div><div class="line">  <a class="code" href="structvalue.html">value</a>&amp; x_menu_id = x_menu[<span class="stringliteral">&quot;id&quot;</span>];</div><div class="line">  USE_VAL(<span class="stringliteral">&quot;$.menu.id&quot;</span>, x_menu_id);</div><div class="line">  <a class="code" href="structvalue.html">value</a>&amp; x_menu_value = x_menu[<span class="stringliteral">&quot;value&quot;</span>];</div><div class="line">  USE_VAL(<span class="stringliteral">&quot;$.menu.value&quot;</span>, x_menu_value);</div><div class="line">  <a class="code" href="structvalue.html">value</a>&amp; x_menu_popup = x_menu[<span class="stringliteral">&quot;popup&quot;</span>];</div><div class="line">  <a class="code" href="structvalue.html">value</a>&amp; x_menu_popup_menuitem = x_menu_popup[<span class="stringliteral">&quot;menuitem&quot;</span>];</div><div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; x_menu_popup_menuitem.<a class="code" href="structvalue.html#aa348b92d0343ec28a56542f2c47dc3aa">size</a>(); i++)</div><div class="line">  {</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; x_menu_popup_menuitemi = x_menu_popup_menuitem[i];</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; x_menu_popup_menuitemi_value = x_menu_popup_menuitemi[<span class="stringliteral">&quot;value&quot;</span>];</div><div class="line">    USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].value&quot;</span>, x_menu_popup_menuitemi_value);</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; x_menu_popup_menuitemi_onclick = x_menu_popup_menuitemi[<span class="stringliteral">&quot;onclick&quot;</span>];</div><div class="line">    USE_VAL(<span class="stringliteral">&quot;$.menu.popup.menuitem[].onclick&quot;</span>, x_menu_popup_menuitemi_onclick);</div><div class="line">  }</div><div class="line">  std::cout &lt;&lt; x &lt;&lt; std::endl;</div><div class="line"></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>JSON values of type <code>value</code> can be easily cast to and from C/C++ types, see <a class="el" href="index.html#cpp-ex">Overview </a> for details.</p>
<p>You can also use the new jsoncpp option <code>-p</code> (gSOAP 2.8.27 and up) to generate efficient JSONPath query code to query and retrieve specific values.</p>
<p>For example, let's write a JSONPath query to display the authors of books in a store. We will read the JSON data from <code>std:cin</code> and filter the authors with the query <code>$.store.book[*].author</code> to collect them in a JSON array <code>y</code> of results with jsoncpp option <code>-y</code>. We generate the code from the command line with jsoncpp as follows: </p><pre class="fragment">jsoncpp -M -p'$.store.book[*].author' -y
</pre><div class="fragment"><div class="line"><a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">std::cin &gt;&gt; x;</div><div class="line"><span class="comment">// JSONPath: $.store.book[*].author</span></div><div class="line"><a class="code" href="structvalue.html">value</a> y(ctx);</div><div class="line">y.size(0);</div><div class="line"><span class="preprocessor">#define QUERY_YIELD(val) y[y.size()] = val</span></div><div class="line"><span class="keywordflow">if</span> (x.has(<span class="stringliteral">&quot;store&quot;</span>))</div><div class="line">{</div><div class="line">  <span class="keywordflow">if</span> (x[<span class="stringliteral">&quot;store&quot;</span>].has(<span class="stringliteral">&quot;book&quot;</span>))</div><div class="line">  {</div><div class="line">    <a class="code" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a> j = x[<span class="stringliteral">&quot;store&quot;</span>][<span class="stringliteral">&quot;book&quot;</span>].begin();</div><div class="line">    <a class="code" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a> k = x[<span class="stringliteral">&quot;store&quot;</span>][<span class="stringliteral">&quot;book&quot;</span>].end();</div><div class="line">    <span class="keywordflow">for</span> (<a class="code" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a> i = j; i != k; ++i)</div><div class="line">    {</div><div class="line">      <span class="keywordflow">if</span> ((*i).has(<span class="stringliteral">&quot;author&quot;</span>))</div><div class="line">      {</div><div class="line">        QUERY_YIELD((*i)[<span class="stringliteral">&quot;author&quot;</span>]);</div><div class="line">      }</div><div class="line">    }</div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>Let's apply this query to the <code>store.json</code> file that you can find in section <a class="el" href="index.html#jsoncpp-4">JSONPath by example </a>: </p><pre class="fragment">./query &lt; store.json
</pre><div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;[</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;Nigel Rees&quot;,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;Evelyn Waugh&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;Herman Melville&quot;,</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;  &quot;J. R. R. Tolkien&quot;</div><div class="line"><a name="l00006"></a><span class="lineno">    6</span>&#160;]</div></div><!-- fragment --> </div><p>You can compile this example yourself with: </p><pre class="fragment">jsoncpp -o query.cpp -m -p'$.store.book[*].author' -y
soapcpp2 -CSL xml-rpc.h
c++ -o query query.cpp json.cpp xml-rpc.cpp soapC.cpp stdsoap2.cpp
</pre><p>You can also embed C/C++ code in JSONPath queries to filter and select values from JSON data at runtime.</p>
<p>The jsoncpp code generator aims to produce clean, high-quality and readable C and C++ code. We will present jsoncpp in more detail in the next section. The remainder of this document explains how you can use the XML-RPC/JSON C and C++ APIs to create JSON data, access JSON data, send/recv data via REST, and to read/write JSON data to files, streams, and string buffers.</p>
<p>It should be stated that JSON as a data format is not a true-and-tested alternative to XML and XML schema. XML data bindings provide a strongly typed interface to exchange validated data with RPC and REST. However, XML can be more complex to provide strong guarantees for object polymorphism (base and derived classes), to accurately represent tree and graph structures, to include binary content natively with base64 (and mechanisms for streaming MIME/MTOM attachments), to support extensibility (to extend data types and to add new data types), and schema namespaces referenced by XML elements and attributes to avoid ambiguity.</p>
<h1><a class="anchor" id="jsoncpp"></a>
The jsoncpp command-line tool                                         </h1>
<p>The jsoncpp command produces high-quality, readable and reusable source code. The generated code can be readily used in your projects to populate JSON data and retrieve data, thereby saving you substantial time and effort to write code. You may not have to write any C or C++ code to manipulate JSON data with your application's code base when taking full advantage of the jsoncpp autocoding tool.</p>
<p>The jsoncpp command-line tool generates C or C++ source code to populate a JSON node graph with the data given in a JSON file. The command also has an option <code>-i</code> to generate source code to inspect parsed JSON values by using a JSON file as a generic template for this code. And option <code>-p</code> generates efficient source code for JSONPath queries. Even stand-alone JSONPath query filter applications can be auto-generated with option <code>-m</code> (for main).</p>
<h2><a class="anchor" id="jsoncpp-1"></a>
Building and installing jsoncpp                                     </h2>
<p>You will find jsoncpp and the XML-RPC/JSON examples in the gSOAP package in <code>gsoap/samples/xml-rpc-json</code>.</p>
<p>To build jsoncpp, <a href="http://www.genivia.com/downloads.html">install gSOAP</a> and build jsoncpp as follows: </p><pre class="fragment">cd gsoap/samples/xml-rpc-json
make jsoncpp
</pre><p>This builds the command-line tool jsoncpp in <code>gsoap/samples/xml-rpc-json</code> from where you can use it and/or copy it for use with your projects.</p>
<p>If you do not have the samples built, you can use soapcpp2 from the command line to generate the C++ code required to compile jsoncpp and that is also required by the C++ JSON API components: </p><pre class="fragment">cd gsoap/samples/xml-rpc-json
soapcpp2 -CSL xml-rpc.h
c++ -I../.. -o jsoncpp jsoncpp.cpp json.cpp xml-rpc.cpp soapC.cpp ../../stdsoap2.cpp
</pre><p>This builds the jsoncpp command-line tool.</p>
<p>For users of Windows, visit <a href="http://www.genivia.com/downloads.html">download and installation</a> to download <code>jsoncpp.exe</code>.</p>
<h2><a class="anchor" id="jsoncpp-2"></a>
Command-line options                                                </h2>
<p>The jsoncpp command takes several options and an optional JSON input file: </p><pre class="fragment">jsoncpp [-c] [-e] [-f%fmt] [-h] [-i] [-k] [-l] [-m] [-M] [-O] [-ofile] [-ppath] [-rroot] [-xcode] [-y] [infile]
</pre><p>where the jsoncpp command-line options are:</p>
<table class="doxtable">
<tr>
<th>Option </th><th>Description  </th></tr>
<tr>
<td><code>-c</code> </td><td>generate C code instead of C++ </td></tr>
<tr>
<td><code>-e</code> </td><td>add explanatory comments to the generated code </td></tr>
<tr>
<td><code>-f%fmt</code></td><td>use <code>%fmt</code> to format double floats, e.g. <code>-f%lG</code> </td></tr>
<tr>
<td><code>-h</code> </td><td>display help message </td></tr>
<tr>
<td><code>-i</code> </td><td>generate code to inspect JSON node graph with data type checks </td></tr>
<tr>
<td><code>-k</code> </td><td>generate code to inspect JSON node graph directly without checks </td></tr>
<tr>
<td><code>-l</code> </td><td>generate code for option <code>-i</code> to store values in local variables </td></tr>
<tr>
<td><code>-m</code> </td><td>generate stand-alone code by adding <code>main()</code> </td></tr>
<tr>
<td><code>-M</code> </td><td>generate minimal code unadorned with initialization and cleanup </td></tr>
<tr>
<td><code>-O</code> </td><td>optimize code by factoring common indices </td></tr>
<tr>
<td><code>-ofile</code> </td><td>save source code to <code>file</code> </td></tr>
<tr>
<td><code>-ppath</code> </td><td>generate JSONPath query code for <code>path</code> </td></tr>
<tr>
<td><code>-rroot</code> </td><td>use <code>root</code> instead of root value <code>x</code> in the generated code </td></tr>
<tr>
<td><code>-xcode</code> </td><td>generate code that executes <code>code</code> for each JSONPath query result </td></tr>
<tr>
<td><code>-y</code> </td><td>generate code that yields an array <code>y</code> of JSONPath query results </td></tr>
<tr>
<td><code>infile</code> </td><td>optional JSON file to parse </td></tr>
<tr>
<td><code>-</code> </td><td>read JSON from standard input </td></tr>
</table>
<p>The jsoncpp command takes a JSON input file <code>infile</code> to generate code to construct this JSON value in C/C++ or, with options <code>-i</code> or <code>-k</code>, to generate code that reads JSON data from input and traverses it to inspect its value by using the JSON input file <code>infile</code> as a template to match against. For options <code>-i</code> and <code>-k</code>, if you want additional code that uses local variables to store boolean, integer, and floating point values retrieved from the JSON node graph, then also use option <code>-l</code>.</p>
<p>Use option <code>-c</code> to generate C code instead of C++ and use option <code>-e</code> to add explanatory comments to the generated code.</p>
<p>The jsoncpp command emits source code to standard output or to the file specified with option <code>-o</code>.</p>
<p>Minimalistic code is generated with option <code>-M</code>, which is useful to automate pasting of the unadorned source code into the source code of your project.</p>
<p>Optimized code is generated with option <code>-O</code> by factoring common array indices and object field names. This produces more elaborate code that is more efficient but may be harder to read and modify. This option has no effect on the code generated with options <code>-i</code> and <code>-k</code>.</p>
<p>The default name of the root value in the generated source code is <code>x</code>. To change this name use option <code>-r</code>. Do not use the name <code>v</code>, which represents the current value. Other variable names to avoid are <code>i</code>, <code>j</code>, <code>k</code>, <code>p</code>, <code>q</code>, <code>r</code>, <code>s</code>, and <code>S</code>, since these are internally used by the generated JSONPath query code.</p>
<p>Use option <code>-p</code> to generate code that filters JSON data from a source of input with a JSONPath query <code>path</code>. Option <code>-x</code> specifies a JSONPath query code to execute for each query result. The default action in the generated code is to print each query result value in JSON format separated by newlines. Option <code>-y</code> yields a JSON array of query result values that are incrementally collected. Option <code>-x</code> overrides option <code>-y</code>.</p>
<p>To generate a stand-alone application use option <code>-m</code>. This option is useful for testing JSONPath query filters given with option <code>-p</code>.</p>
<p>Option <code>-f%fmt</code> sets the floating point double precision format to use in the generated code. By default, jsoncpp emits floating point numbers with up to 17 digit mantissas to preserve precision. Use <code>-f%lG</code> for the shortest floating point representation.</p>
<h2><a class="anchor" id="jsoncpp-3"></a>
JSONPath syntax                                                     </h2>
<p>The concept behind JSONPath is identical to XPath for XML: to select elements (value nodes) from a DOM node structure of a document by matching the path expression against descendent nodes in the node tree structure. A JSONPath query returns the JSON values selected.</p>
<p>We adopt the JSONPath syntax suggested by <a href="http://goessner.net/articles/JsonPath">Goessner</a>, but extended with <code>?</code> ("where") and <code>!</code> ("where not") operators. Our JSONPath syntax also supports the <code>[?(expr)]</code> and <code>[(expr)]</code> constructs to insert your own C/C++ expressions for filtering and selection of nodes in JSONPath queries. Our syntax also supports multiple comma-separated alternatives in the <code>[ ]</code> selector. But the syntax does not support <code>|</code> (alternation). We recommend to write a JSONPath query for each alternation.</p>
<p>JSON data structures are represented internally as a node graph consisting of atomic values (null, bool, int/double, string), arrays, and "objects". JSON objects are structs with fieldname-value pairs. A JSONPath expression specifies a JSON data query, typically starting from the root node, and descending deeper into the node graph to match child nodes.</p>
<p>For example, suppose we have a <code>store</code> object with a <code>book</code> array. Each <code>book</code> object has a <code>title</code> string and some other properties which we will ignore for now. The following JSONPath query returns the titles of all books in the store: </p><pre class="fragment">$.store.book[*].title
</pre><p>We can also write the same query in bracket notation: </p><pre class="fragment">$["store"]["book"][*]["title"]
</pre><p>Note that the syntax of this query has a close similarity to the C++ JSON API for accessing object fields (a.k.a. object properties) and array elements.</p>
<p>Basically, a JSONPath expression is a sequence of operations to match nodes:</p>
<table class="doxtable">
<tr>
<th>Operator </th><th>Nodes matched and returned  </th></tr>
<tr>
<td><code>$</code> </td><td>the root node of the node graph </td></tr>
<tr>
<td><code>.f</code> or <code>[f]</code> </td><td>child node at field named <code>f</code> of the current object node </td></tr>
<tr>
<td><code>[n]</code> </td><td>nth node of the current array node, if indexed within bounds </td></tr>
<tr>
<td><code>[b:e:s]</code> </td><td>array slice of the current array node </td></tr>
<tr>
<td><code>[x,y]</code> </td><td>child nodes matching <code>x</code> or <code>y</code> (fields, indices and slices) </td></tr>
<tr>
<td><code>*</code> </td><td>"wildcard": any child node of the current object/array node </td></tr>
<tr>
<td><code>..</code> </td><td>"recurse": any matching descendant nodes of the current node </td></tr>
<tr>
<td><code>?</code> </td><td>"where": current node if the rest of the query path matches </td></tr>
<tr>
<td><code>!</code> </td><td>"where not": the complement of <code>?</code> </td></tr>
<tr>
<td><code>[(e)]</code> </td><td>use value of C/C++ expression <code>e</code> to match a field or index </td></tr>
<tr>
<td><code>[?(e)]</code> </td><td>evaluate C/C++ expression <code>e</code>, continue matching when true </td></tr>
</table>
<p>Field names (<code>f</code> in the table) in JSON and in JSONPath queries may contain UTF-8 Unicode characters.</p>
<p>Throughout this document we refer to the <em>field names</em> of objects and structs. Also commonly used are JSON object <em>property names</em> and <em>key names</em> (as in key-value pairs),</p>
<p>Other JSONPath implementations require quotes for field names in brackets, as in <code>["store"]</code>. With jsoncpp you will only need to add quotes when field names contain control characters, spaces, or punctuation, such as a <code>unit-price</code> field name in the query <code>$..["unit-price"]</code>. To promote orthogonality of the JSONPath syntax (no arbitrary rules and exceptions depending on a context), quoted field names are also valid with dot notation in our JSONPath syntax, such as the query <code>$.."unit-price"</code>.</p>
<h2><a class="anchor" id="jsoncpp-4"></a>
JSONPath by example                                                 </h2>
<p>A JSONPath query expression uses dot or bracket operators to match JSON data located at increasingly deeper levels of the data structure.</p>
<p>Consider the following JSON data:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;store&quot;: {</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;    &quot;book&quot;: [ </div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;      {</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;        &quot;category&quot;: &quot;reference&quot;,</div><div class="line"><a name="l00006"></a><span class="lineno">    6</span>&#160;        &quot;author&quot;: &quot;Nigel Rees&quot;,</div><div class="line"><a name="l00007"></a><span class="lineno">    7</span>&#160;        &quot;title&quot;: &quot;Sayings of the Century&quot;,</div><div class="line"><a name="l00008"></a><span class="lineno">    8</span>&#160;        &quot;price&quot;: 8.95</div><div class="line"><a name="l00009"></a><span class="lineno">    9</span>&#160;      },</div><div class="line"><a name="l00010"></a><span class="lineno">   10</span>&#160;      {</div><div class="line"><a name="l00011"></a><span class="lineno">   11</span>&#160;        &quot;category&quot;: &quot;fiction&quot;,</div><div class="line"><a name="l00012"></a><span class="lineno">   12</span>&#160;        &quot;author&quot;: &quot;Evelyn Waugh&quot;,</div><div class="line"><a name="l00013"></a><span class="lineno">   13</span>&#160;        &quot;title&quot;: &quot;Sword of Honour&quot;,</div><div class="line"><a name="l00014"></a><span class="lineno">   14</span>&#160;        &quot;price&quot;: 12.99</div><div class="line"><a name="l00015"></a><span class="lineno">   15</span>&#160;      },</div><div class="line"><a name="l00016"></a><span class="lineno">   16</span>&#160;      {</div><div class="line"><a name="l00017"></a><span class="lineno">   17</span>&#160;        &quot;category&quot;: &quot;fiction&quot;,</div><div class="line"><a name="l00018"></a><span class="lineno">   18</span>&#160;        &quot;author&quot;: &quot;Herman Melville&quot;,</div><div class="line"><a name="l00019"></a><span class="lineno">   19</span>&#160;        &quot;title&quot;: &quot;Moby Dick&quot;,</div><div class="line"><a name="l00020"></a><span class="lineno">   20</span>&#160;        &quot;isbn&quot;: &quot;0-553-21311-3&quot;,</div><div class="line"><a name="l00021"></a><span class="lineno">   21</span>&#160;        &quot;price&quot;: 8.99</div><div class="line"><a name="l00022"></a><span class="lineno">   22</span>&#160;      },</div><div class="line"><a name="l00023"></a><span class="lineno">   23</span>&#160;      {</div><div class="line"><a name="l00024"></a><span class="lineno">   24</span>&#160;        &quot;category&quot;: &quot;fiction&quot;,</div><div class="line"><a name="l00025"></a><span class="lineno">   25</span>&#160;        &quot;author&quot;: &quot;J. R. R. Tolkien&quot;,</div><div class="line"><a name="l00026"></a><span class="lineno">   26</span>&#160;        &quot;title&quot;: &quot;The Lord of the Rings&quot;,</div><div class="line"><a name="l00027"></a><span class="lineno">   27</span>&#160;        &quot;isbn&quot;: &quot;0-395-19395-8&quot;,</div><div class="line"><a name="l00028"></a><span class="lineno">   28</span>&#160;        &quot;price&quot;: 22.99</div><div class="line"><a name="l00029"></a><span class="lineno">   29</span>&#160;      }</div><div class="line"><a name="l00030"></a><span class="lineno">   30</span>&#160;    ],</div><div class="line"><a name="l00031"></a><span class="lineno">   31</span>&#160;    &quot;bicycle&quot;: {</div><div class="line"><a name="l00032"></a><span class="lineno">   32</span>&#160;      &quot;color&quot;: &quot;red&quot;,</div><div class="line"><a name="l00033"></a><span class="lineno">   33</span>&#160;      &quot;price&quot;: 19.95</div><div class="line"><a name="l00034"></a><span class="lineno">   34</span>&#160;    }</div><div class="line"><a name="l00035"></a><span class="lineno">   35</span>&#160;  }</div><div class="line"><a name="l00036"></a><span class="lineno">   36</span>&#160;}</div></div><!-- fragment --> </div><p>To match the <code>title</code> of the first book (<code>book[0]</code>) in a <code>store</code>, starting at the root node indicated by <code>$</code>, we use the following JSONPath query expression: </p><pre class="fragment">$.store.book[0].title
</pre><p>This query returns <code>"Sayings of the Century"</code> when applied to the JSON data.</p>
<p>To try the JSONPath examples yourself, we suggest to create a <code>store.json</code> file with the above JSON data and run jsoncpp from the command line to compile a JSONPath query as follows: </p><pre class="fragment">cd gsoap/samples/xml-rpc-json
soapcpp2 -CSL xml-rpc.h
jsoncpp -o test-json.cpp -m -p'$.store.book[0].title'
c++ -I../.. -o test-json test-json.cpp json.cpp xml-rpc.cpp soapC.cpp ../../stdsoap2.cpp
./test-json &lt; store.json
</pre><p>The compiled JSONPath query is applied to the <code>store.json</code> data and returns the matching values found. Use jsoncpp option <code>-y</code> to return matches in a JSON array.</p>
<p>The <code>soapC.cpp</code> file, and the header files <code>soapStub.h</code> and <code>soapH.h</code>, are generated with the command <code>soapcpp2 -CSL <a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>, which is done just once for all C++ JSON applications. Use soapcpp2 option <code>-c</code> to generate <code>soapC.c</code> for C (with the corresponding <code>soapStub.h</code> and <code>soapH.h</code> in C).</p>
<p>To match any field of an object or any array element, we use a wildcard <code>*</code>: </p><pre class="fragment">$.store.*.price
</pre><p>This matches and returns the bicycle price <code>19.95</code>, but not the book prices that are located one level deeper in the array of books, which can be matched with: </p><pre class="fragment">$.store.*.*.price
</pre><p>This returns the values <code>8.95</code>, <code>12.99</code>, <code>8.99</code>, and <code>22.99</code>.</p>
<p>Note that in the latter case we only get the book prices, because the first <code>*</code> matches <code>book</code> and <code>bicycle</code> and the second <code>*</code> matches the book array and the <code>red</code> and <code>price</code> fields. Only the book prices are returned, because <code>red</code> and <code>price</code> are atomic and have no <code>price</code> child node.</p>
<p>To match and return all prices in the store we use <code>..</code> called "recursive
descent" or simply "recurse", as follows: </p><pre class="fragment">$..price
</pre><p>Array elements are matched with brackets <code>[n]</code> where <code>n</code> is an array index. Negative indices can be used to access array elements from the end of an array, where -1 refers to the last element. We can list the array elements to match with <code>[x,y]</code>, for example: </p><pre class="fragment">$.store.book[0,1,-1].title
</pre><p>This matches and returns the titles of the first two books and the last.</p>
<p>JSONPath queries do not modify the node graph searched. So you do not need to worry about indices that are out of bounds or fields that are not part of an object.</p>
<p>Arrays can also be sliced for matching from a starting index <code>b</code> until (excluding) an ending index <code>e</code> with <code>[b:e]</code>, where <code>b</code> and <code>e</code> values are optional. When omitted, the slice runs from the start and/or from the end of the array.</p>
<p>For example: </p><pre class="fragment">$.store.book[:].title
</pre><p>matches and returns the titles of all books in the store, and </p><pre class="fragment">$.store.book[:2].title
</pre><p>matches and returns the first two books (at 0 and 1) in the store.</p>
<p>We can use an optional step <code>s</code> to slice arrays with <code>[b:e:s]</code> and even reverse array element-by-element matching with a negative unit step: </p><pre class="fragment">$.store.book[::-1].title
</pre><p>This matches and returns the titles of all books in reverse order.</p>
<p>The following JSONPath queries return the same results for the example JSON data, where we used slices and <code>[x,y]</code> to match multiple array entries: </p><pre class="fragment">$.store.book[1:3].title
$.store.book[1:-1].title
$.store.book[-3:-1].title
$.store.book[1,2].title
$.store.book[-3,-2].title
</pre><p>Basically, JSONPath array slices in our implementation follow the intuitive Python array slice syntax and meaning. Beware that many other JSONPath implementations do not implement the step parameter consistently or do not support stepping.</p>
<p>Note that <code>[:]</code> is not the same as <code>[*]</code> because <code>[:]</code> only matches arrays.</p>
<p>A conditional JSONPath expression contains a <code>?</code> ("where") operator. The operator returns the results that match the left side of the <code>?</code> but only when the right-side matches: </p><pre class="fragment">$.store.book[:]?isbn
</pre><p>This matches and returns only books that have an <code>isbn</code> field.</p>
<p>The complement of the <code>?</code> operator is <code>!</code> ("where not"), which returns the results that match the left side of the <code>!</code> but only when the right-side does not match.</p>
<p>More complex queries can be formulated by embedding C/C++ expressions in the query to filter <code>[?(e)]</code> and select <code>[(e)]</code> nodes. For example, in C++: </p><pre class="fragment">$.store.book[:][?((double)v["price"] &lt; 10.0)].title
</pre><p>and in C: </p><pre class="fragment">$.store.book[:][?(*double_of(value_at(v, "price")) &lt; 10.0)].title
</pre><p>This filters books with prices lower than 10.0 and returns the title of each book found.</p>
<p>Embedded C/C++ expressions to filter nodes can inspect the current JSONPath node value by accessing variable <code>v</code>, as is shown above. Here we used <code>(double)v["price"]</code> to obtain the price of the current node for comparison. Besides the current node <code>v</code> you can also access the JSONPath root node value <code>x</code>. Instead of the default name <code>x</code>, you can change <code>x</code> to another name with jsoncpp option <code>-r</code>.</p>
<p>You can access variables and functions in embedded C/C++ expressions, but do not access or modify <code>i</code>, <code>j</code>, <code>k</code>, <code>p</code>, <code>q</code>, <code>r</code>, <code>s</code> and <code>S</code>, which are internally used by the generated JSONPath query code.</p>
<dl class="section warning"><dt>Warning</dt><dd>In this respect we should caution you about using C/C++ expressions that modify node values, since this may affect the query results in unpredictable ways. In fact, <code>v["price"]</code> will add a price to any current node value <code>v</code> that has no <code>"price"</code> field! To make field accesses safe we should first check if the field exists in the current node before we access it: <pre class="fragment">$.store.book[:][?((v.has("price") ? (double)v["price"] : 9999) &lt; 10.0)].title
</pre></dd>
<dd>
Guarding field accesses with <code>has()</code> is the only safe way to combine <code>..</code> with C/C++ filters, since we may visit all nodes in the graph, for example to find all prices &lt; 10.0: <pre class="fragment">$..[?((v.has("price") ? (double)v["price"] : 9999) &lt; 10.0)].price
</pre></dd></dl>
<p>Object fields and array elements can be accessed in a JSONPath query with C/C++ expressions that evaluate to string field names or to integers indices, respectively. For example, we can use the string <code>argv[1]</code> of <code>main()</code> as a field name in C++: </p><pre class="fragment">$.store.book[:][(argv[1])]
</pre><p>In C we have to explicitly use <code>value_at</code> to access the field of the current <code>v</code> node (and we use <code>nth_value</code> to access array elements of the current <code>v</code> node, not shown here): </p><pre class="fragment">$.store.book[:][(value_at(v, argv[1]))]
</pre><p>This assumes that the command-line argument (<code>argv[1]</code>) of the application is a book field name. Otherwise, no results are returned.</p>
<p>After compiling the JSONPath query with </p><pre class="fragment">jsoncpp -o test-json.cpp -m -p'$.store.book[:][(argv[1])]'
c++ -I../.. -o test-json test-json.cpp json.cpp xml-rpc.cpp soapC.cpp ../../stdsoap2.cpp
</pre><p>we can obtain the book titles with: </p><pre class="fragment">./test-json title &lt; store.json
</pre><p>You can use multiple C/C++ expressions in brackets and combine them with other field and array expressions separated by commas: </p><pre class="fragment">$.store.book[:][title,(argv[1])]
</pre><p>This prints the title and the value of the field name given by the command-line argument, if there is a field that matches the given name.</p>
<p>Finally, let's use the value of <code>argv</code> to filter products in the store by a given command-line argument price: </p><pre class="fragment">jsoncpp -m -p'$.store..[?((v.has("price") ? (double)v["price"] : 9999) &lt; strtod(argv[1], NULL))]'
</pre><p>And in C: </p><pre class="fragment">jsoncpp -c -m -p'$.store..[?((nth_at(v, "price") &gt;= 0 ? *double_of(value_at(v, "price")) : 9999) &lt; strtod(argv[1], NULL))]'
</pre><p>C/C++ expressions cannot be used as array slice bounds, which must be constant.</p>
<h1><a class="anchor" id="cpp"></a>
C++ XML-RPC and JSON                                                      </h1>
<p>XML-RPC and JSON data is interchangeable in this implementation, with the only exception that the dateTime and base64 types are handled as strings in JSON. Also, JSON's only numeric type is floating point. However, integers are handled just fine by this JSON implementation as 64 bit (i.e. <code>long long</code>, <code>int64_t</code>, <code>LONG64</code>) without internal conversion to/from double floating point values that could cause a loss of precision for large values.</p>
<h2><a class="anchor" id="cpp-files"></a>
List of files                                                       </h2>
<p>The following files define XML-RPC operations and data types for C++:</p>
<ul>
<li><code>xml-rpc-io.h</code>: XML-RPC serialization over streams</li>
<li><code>xml-rpc-io.cpp</code>: XML-RPC serialization over streams</li>
<li><code><a class="el" href="xml-rpc-iters_8h.html">xml-rpc-iters.h</a></code>: iterators for structs, arrays, and XML-RPC parameters</li>
<li><code>xml-rpc.cpp</code>: XML-RPC C++ data binding API</li>
<li><code><a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>: XML-RPC data binding as a gSOAP .h file for soapcpp2 (do not #include this file in your project builds)</li>
</ul>
<p>For JSON we use the following files for C++:</p>
<ul>
<li><code><a class="el" href="json_8h.html">json.h</a></code>: JSON C++ API and JSON serialization over streams</li>
<li><code>json.cpp</code>: JSON C++ API and JSON serialization over streams</li>
<li><code>xml-rpc.cpp</code>: XML-RPC C++ data binding API</li>
<li><code><a class="el" href="xml-rpc-iters_8h.html">xml-rpc-iters.h</a></code>: iterators for structs/objects and arrays</li>
<li><code><a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>: XML-RPC data binding as a gSOAP .h file for soapcpp2 (do not #include this file in your project builds)</li>
</ul>
<p>The gSOAP header file <code><a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code> defines all XML-RPC and JSON types as struct with C++ member functions to create XML-RPC and JSON data and REST messages.</p>
<p>A note about the following auto-generated files: <code>soapH.h</code>, <code>soapStub.h</code> and <code>soapC.cpp</code>. These are required for XML-RPC and JSON. To auto-generate these files, execute: </p><pre class="fragment">soapcpp2 -CSL xml-rpc.h
</pre><p>Then compile and link the <code>.cpp</code> files listed above for XML-RPC and JSON with the auto-generated <code>soapC.cpp</code> and <code>stdsoap2.cpp</code>: </p><pre class="fragment">c++ -I../.. -o myapp myapp.cpp json.cpp xml-rpc.cpp soapC.cpp ../../stdsoap2.cpp
</pre><p>Instead of <code>stdsoap2.cpp</code> you can link <code>libgsoap++.a</code> with <code>-lgsoap++</code>, when installed by the gSOAP package.</p>
<p>To enable OpenSSL for HTTPS compile with <code>-DWITH_OPENSSL</code> and link <code>-lssl</code>, and <code>-lcrypto</code>: </p><pre class="fragment">c++ -DWITH_OPENSSL -I../.. -o myapp myapp.cpp json.cpp xml-rpc.cpp soapC.cpp ../../stdsoap2.cpp -lssl -lcrypto
</pre><p>For OpenSSL support, instead of <code>stdsoap2.cpp</code> you can link <code>libgsoapssl++.a</code> with <code>-lgsoapssl++</code>, when installed by the gSOAP package.</p>
<p>Because XML namespaces are not used, we can either use <code>-DWITH_NONAMESPACES</code> to compile <code>stdsoap2.cpp</code> without complaining about a missing global <code>Namespace</code>, or we can define an empty namespaces table somewhere in our code:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}};</div></div><!-- fragment --><h2><a class="anchor" id="cpp-ex"></a>
Overview                                                               </h2>
<p>An XML-RPC/JSON data value is created in C++ as follows, which requires a context <code>ctx</code> with the engine state (the soap struct). The context manages the memory that is internally allocated to hold values:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span></div><div class="line"></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING);  <span class="comment">// new context</span></div><div class="line"></div><div class="line"><a class="code" href="structvalue.html">value</a> v(ctx);       <span class="comment">// a new local value v</span></div><div class="line"></div><div class="line">soap_destroy(ctx);  <span class="comment">// delete all values</span></div><div class="line">soap_end(ctx);      <span class="comment">// delete temp data</span></div><div class="line">soap_free(ctx);     <span class="comment">// free context</span></div></div><!-- fragment --><p>Note that <code>soapH.h</code> is an auto-generated file (see previous section). This file needs to be generated only once and for all. It also references <code>stdsoap2.h</code> and the auto-generated <code>soapStub.h</code>. Compile and link your code with <code>stdsoap2.cpp</code> and the auto-generated <code>soapC.cpp</code> XML-RPC serializers. Also compile and link <code>xml-rpc.cpp</code>. For JSON, compile and link <code>json.cpp</code>.</p>
<p>We can stack-allocate local values as shown above. To allocate a value on the heap that is managed by the engine context, use <code>new_value(ctx)</code>:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span></div><div class="line"></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING);  <span class="comment">// new context</span></div><div class="line"></div><div class="line"><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"></div><div class="line">soap_destroy(ctx);  <span class="comment">// delete all values</span></div><div class="line">soap_end(ctx);      <span class="comment">// delete temp data</span></div><div class="line">soap_free(ctx);     <span class="comment">// free context</span></div></div><!-- fragment --><p>Allocating values on the heap may throw <code>std::bad_alloc</code> exceptions, but allocating a context does not. To safeguard your code use a try-catch:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span></div><div class="line"></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING);  <span class="comment">// new context (does not throw)</span></div><div class="line"><span class="keywordflow">if</span> (ctx == NULL)</div><div class="line">  ...               <span class="comment">// handle out-of-memory error</span></div><div class="line"></div><div class="line"><span class="keywordflow">try</span> {</div><div class="line"></div><div class="line">  <a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  ...               <span class="comment">// create other values</span></div><div class="line"></div><div class="line">}</div><div class="line"><span class="keywordflow">catch</span> (std::bad_alloc&amp; e)</div><div class="line">{</div><div class="line">  ...               <span class="comment">// handle out-of-memory error</span></div><div class="line">}</div><div class="line"></div><div class="line">soap_destroy(ctx);  <span class="comment">// delete all values</span></div><div class="line">soap_end(ctx);      <span class="comment">// delete temp data</span></div><div class="line">soap_free(ctx);     <span class="comment">// free context</span></div></div><!-- fragment --><p>You can use wide strings with Unicode stored in UTF-8-formattted 8-bit <code>char</code> strings. For compatibility with XML-RPC serialization of UTF-8-encoded strings, we MUST use the <code>SOAP_C_UTFSTRING</code> flag to initialize the context with <code>soap_new1(SOAP_C_UTFSTRING)</code>. We can optionally use <code>SOAP_XML_INDENT</code> to indent XML and JSON.</p>
<p>The code shown above creates an empty value <code>v</code>. Values can be assigned any one of the following data types:</p>
<div class="fragment"><div class="line">v = 12345LL;          <span class="comment">// 64 bit int</span></div><div class="line"></div><div class="line">v = 12.34;            <span class="comment">// double float</span></div><div class="line"></div><div class="line">v = <span class="stringliteral">&quot;abc&quot;</span>;            <span class="comment">// string</span></div><div class="line"></div><div class="line">v = string(<span class="stringliteral">&quot;abc&quot;</span>);    <span class="comment">// std::string</span></div><div class="line"></div><div class="line">v = L<span class="stringliteral">&quot;xyz&quot;</span>;           <span class="comment">// wide string (converted to UTF-8)</span></div><div class="line"></div><div class="line">v = wstring(L<span class="stringliteral">&quot;xyz&quot;</span>);  <span class="comment">// std::wstring (converted to UTF-8)</span></div><div class="line"></div><div class="line">v = <span class="keyword">false</span>;            <span class="comment">// Boolean</span></div><div class="line"></div><div class="line">v = (ULONG64)time(0); <span class="comment">// ULONG64 values are serialized as ISO 8601 date time</span></div><div class="line"></div><div class="line"><span class="comment">// create an array [24, 99.99, &quot;abc&quot;]</span></div><div class="line">v[0] = 24;</div><div class="line">v[1] = 99.99;</div><div class="line">v[2] = <span class="stringliteral">&quot;abc&quot;</span>;</div><div class="line"></div><div class="line"><span class="comment">// copy a C array or a C++ container to a JSON array</span></div><div class="line"><span class="keywordtype">int</span> ints[] = { 1, 2, 3 };</div><div class="line">v.<a class="code" href="structvalue.html#aa348b92d0343ec28a56542f2c47dc3aa">size</a>(3);            <span class="comment">// array size of JSON value v must conform</span></div><div class="line">std::copy(ints, ints + 3, v.<a class="code" href="structvalue.html#a0f72d8e5406f3349b26de14831b4172f">begin</a>());</div><div class="line"></div><div class="line"><span class="comment">// create a struct (JSON object) {&quot;name&quot;: &quot;gsoap&quot;, &quot;major&quot;: 2.8, &quot;©&quot;: 2015}</span></div><div class="line">v[<span class="stringliteral">&quot;name&quot;</span>]  = <span class="stringliteral">&quot;gsoap&quot;</span>;</div><div class="line">v[<span class="stringliteral">&quot;major&quot;</span>] = 2.8;</div><div class="line">v[L<span class="stringliteral">&quot;©&quot;</span>]    = 2015;    <span class="comment">// wide string tags are OK</span></div><div class="line"></div><div class="line"><span class="comment">// create a base64-encoded image object</span></div><div class="line"><a class="code" href="struct__base64.html">_base64</a> img(ctx, 100, ptr_to_rawimage100bytes); <span class="comment">// block of 100 raw bytes</span></div><div class="line">v = img;</div></div><!-- fragment --><p>We can combine these operations in many possible ways to create arrays of arrays, arrays of structs, and so on. For example:</p>
<div class="fragment"><div class="line">v[0][<span class="stringliteral">&quot;name&quot;</span>] = <span class="stringliteral">&quot;bob&quot;</span>;</div><div class="line">v[0][<span class="stringliteral">&quot;toys&quot;</span>][0] = <span class="stringliteral">&quot;ball&quot;</span>;</div><div class="line">v[0][<span class="stringliteral">&quot;toys&quot;</span>][1] = <span class="stringliteral">&quot;furby&quot;</span>;</div></div><!-- fragment --><p>This creates a singleton array containing an object with two members: <code>name</code> set to <code>"bob"</code> and <code>toys</code> set to an array containing <code>"ball"</code> and <code>"furby"</code>. In JSON format this is represented as: </p><pre class="fragment">           [ { "name": "bob", "toys": ["ball", "furby"] } ]
           ^ ^ ^              ^
           | | |              |
  an array_/ | |              |
 of 1 struct_/ |              |
with 2 members_/______________/
</pre><p>Let's see what happens when we assign a variable the value of another.</p>
<p>The JSON C++ API uses the <em>value model</em> for variables with atomic values, meaning that atomic values are copied when assigning a target variable the atomic value of another variable. It uses the <em>reference model</em> for arrays and structs, meaning that array and struct contents are shared when assigning a target variable the array/struct value of another variable. We illustrate the effect below:</p>
<div class="fragment"><div class="line"><a class="code" href="structvalue.html">value</a> x(ctx), y(ctx);</div><div class="line">x = 1;</div><div class="line">y = x;</div><div class="line">x = 2;</div><div class="line">std::cout &lt;&lt; <span class="stringliteral">&quot;x = &quot;</span> &lt;&lt; x &lt;&lt; <span class="stringliteral">&quot; and y = &quot;</span> &lt;&lt; y &lt;&lt; std::endl;</div><div class="line"><a class="code" href="structvalue.html">value</a> a(ctx), b(ctx);</div><div class="line">a[<span class="stringliteral">&quot;num&quot;</span>] = 1;</div><div class="line">b = a;</div><div class="line">a[<span class="stringliteral">&quot;num&quot;</span>] = 2;</div><div class="line">std::cout &lt;&lt; <span class="stringliteral">&quot;a.num = &quot;</span> &lt;&lt; a[<span class="stringliteral">&quot;num&quot;</span>] &lt;&lt; <span class="stringliteral">&quot; and b.num = &quot;</span> &lt;&lt; b[<span class="stringliteral">&quot;num&quot;</span>] &lt;&lt; std::endl;</div></div><!-- fragment --><p>This prints <code>x = 2 and y = 1</code> and <code>a.num = 2 and b.num = 2</code>.</p>
<p>You can make deep copies of values by using the auto-generated <code>soap_dup_value</code> function in <code>soapC.cpp</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="structvalue.html">value</a> a(ctx), b(ctx);</div><div class="line">a[<span class="stringliteral">&quot;num&quot;</span>] = 1;</div><div class="line">soap_dup_value(ctx, &amp;b, &amp;a);</div><div class="line">a[<span class="stringliteral">&quot;num&quot;</span>] = 2;</div><div class="line">std::cout &lt;&lt; <span class="stringliteral">&quot;a.num = &quot;</span> &lt;&lt; a[<span class="stringliteral">&quot;num&quot;</span>] &lt;&lt; <span class="stringliteral">&quot; and b.num = &quot;</span> &lt;&lt; b[<span class="stringliteral">&quot;num&quot;</span>] &lt;&lt; std::endl;</div></div><!-- fragment --><p>This prints <code>a.num = 2 and b.num = 1</code>.</p>
<dl class="section warning"><dt>Warning</dt><dd>Do not extend arrays and structs (JSON objects) returned by <code>soap_dup_value</code> with new entries. The new entries may use unallocated memory. You can always loop over arrays and structs to copy their contents to a new array or struct managed by another context, if you must add new entries later.</dd></dl>
<p>To auto-generate <code>soap_dup_value</code>, use option <code>-Ec</code> with soapcpp2: </p><pre class="fragment">soapcpp2 -Ec -CSL xml-rpc.h
</pre><p>With gSOAP 2.8.28 and later you can use the following operators on values in C++:</p>
<table class="doxtable">
<tr>
<th>Operator </th><th>Type of JSON Value Operands </th><th>Result after Operand Type Promotion  </th></tr>
<tr>
<td><code>+</code> </td><td>bool, number, string, struct, array </td><td>sum, string concat, struct concat, array concat </td></tr>
<tr>
<td><code>-</code>, <code>*</code>, <code>/</code>, <code>%</code> </td><td>bool, number </td><td>difference, product, division, modulo </td></tr>
<tr>
<td><code>==</code>, <code>!=</code> </td><td>bool, number, string, struct, array </td><td>C++ <code>bool</code> </td></tr>
<tr>
<td><code>&lt;=</code>, <code>&gt;=</code>, <code>&lt;</code>, <code>&gt;</code> </td><td>bool, number, string </td><td>C++ <code>bool</code> </td></tr>
</table>
<p>The (un)equal operators compare the two values by deep value comparison of array elements and object fields and values. For the arithmetic operations, operands are converted by type promotion until the two operands conform to the type required for the operation: </p><pre class="fragment">atomic   int    double    string    struct    array

false -&gt; 0
true  -&gt; 1
         int -&gt; double
null -------------------&gt; "null"
false ------------------&gt; "false"
true -------------------&gt; "true"
         int -&gt; double -&gt; string
null ---------------------------------------&gt; [null]
false --------------------------------------&gt; [false]
true ---------------------------------------&gt; [true]
         int -------------------------------&gt; [int]
                double ---------------------&gt; [double]
                          string -----------&gt; [string]
                                    struct -&gt; [struct]
</pre><p>An example:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;sstream&gt;</span></div><div class="line">std::stringstream ss(<span class="stringliteral">&quot;[0,1,2]&quot;</span>);</div><div class="line"></div><div class="line"><span class="comment">// parse JSON array into &#39;x&#39;</span></div><div class="line"><a class="code" href="structvalue.html">value</a> x(ctx);</div><div class="line">ss &gt;&gt; x;            <span class="comment">// x = [0,1,2]</span></div><div class="line">x[3] = x[1] + x[2]; <span class="comment">// x = [0,1,2,3]</span></div><div class="line"></div><div class="line"><a class="code" href="structvalue.html">value</a> y(ctx);</div><div class="line">y[0] = <span class="stringliteral">&quot;abc&quot;</span>;       <span class="comment">// y = [&quot;abc&quot;]</span></div><div class="line">y[1] = y[0] + 123;  <span class="comment">// y = [&quot;abc&quot;,&quot;abc123&quot;]</span></div><div class="line"></div><div class="line">std::cout &lt;&lt; x + y; <span class="comment">// [0,1,2,3] + [&quot;abc&quot;,&quot;abc123&quot;] is [0,1,2,3,&quot;abc&quot;,&quot;abc123&quot;]</span></div></div><!-- fragment --><p>Arithmetic and concatenation operations may incur significant memory overhead due to temporaries, type conversions (when applicable), and managed heap storage. Use them only when CPU and memory usage are not critical.</p>
<p>When receiving a value in XML-RPC/JSON, we generally want to check its type to obtain its value. To check the type of a value, we use <code>is_Type</code> methods:</p>
<div class="fragment"><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html#a98b46005862c3378fa0f514876ac6967">value::is_null</a>()     <span class="comment">// true if value is not set (JSON null)</span></div><div class="line">bool <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a641eee093203fbd4a308e92b9eee1238">is_bool</a>()     <span class="comment">// true if value is a Boolean &quot;true&quot; or &quot;false&quot; value</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a56a91404bf315af6dfe31786924dcd80">is_true</a>()     <span class="comment">// true if value is Boolean &quot;true&quot;</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#aab4f39a727533199bc25a0dd57e539e7">is_false</a>()    <span class="comment">// true if value is Boolean &quot;false&quot;</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a26f8409f8dd1b093bea7dbd036392be0">is_number</a>()   <span class="comment">// true if value is a number (int or float)</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb">is_int</a>()      <span class="comment">// true if value is a 32 or a 64 bit int</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028">is_double</a>()   <span class="comment">// true if value is a 64 bit double floating point (not integer)</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>()   <span class="comment">// true if value is a string or wide string</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a06cf4ad42a3483b8a0da51f77aefa2bd">is_dateTime</a>() <span class="comment">// true if ISO 8601, always false for received JSON</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>()    <span class="comment">// true if array of values</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>()   <span class="comment">// true if structure, a.k.a. a JSON object</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::<a class="code" href="xml-rpc_8h.html#a99a7e4bbd0637ef4e752896cf299cfb7">is_base64</a>()   <span class="comment">// true if base64, always false for received JSON</span></div></div><!-- fragment --><p>When working with JSON data, do not use <code><a class="el" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028" title="C function returns true if value is a 64 bit double floating point. ">is_double()</a></code> but <code><a class="el" href="xml-rpc_8h.html#a26f8409f8dd1b093bea7dbd036392be0" title="C function returns true if value is a number (int or float) ">is_number()</a></code>. JSON data does not differentiate between integers and floats. However, gSOAP makes sure that 64 bit integer values are accurately represented in JSON and decoded without loss from JSON. That is, when receiving an integer that you checked with <code><a class="el" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb" title="C function returns true if value is a 32 or a 64 bit int. ">is_int()</a></code> you can then safely cast value with e.g. <code>int64_t n = v</code>.</p>
<p>The following methods can be used to inspect arrays and structs (JSON objects):</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> <a class="code" href="structvalue.html#a2db9152a4f86289696a72bd13e26e7b9">value::size</a>(<span class="keywordtype">int</span>)                  <span class="comment">// reset array size or pre-allocate space</span></div><div class="line">int <a class="code" href="structvalue.html">value</a>::size()                      <span class="comment">// returns array or struct size or 0</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::empty()                    <span class="comment">// true if array or struct is empty</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::has(<span class="keywordtype">int</span>)                   <span class="comment">// true if index is within array bounds</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::has(const <span class="keywordtype">char</span>*)           <span class="comment">// true if struct has field</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structvalue.html">value</a>::has(const <span class="keywordtype">wchar_t</span>*)        <span class="comment">// true if struct has field</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="structvalue.html">value</a>::nth(<span class="keywordtype">int</span>)                    <span class="comment">// returns index &gt;= 0 if index is in array bounds, &lt; 0 otherwise</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="structvalue.html">value</a>::nth(const <span class="keywordtype">char</span>*)            <span class="comment">// returns index &gt;= 0 of field in struct, &lt; 0 otherwise</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="structvalue.html">value</a>::nth(const <span class="keywordtype">wchar_t</span>*)         <span class="comment">// returns index &gt;= 0 of field in struct, &lt; 0 otherwise</span></div><div class="line"><a class="code" href="structvalue.html">value</a>&amp; <a class="code" href="structvalue.html">value</a>::operator[<span class="keywordtype">int</span>]            <span class="comment">// returns value at index in array or struct</span></div><div class="line"><a class="code" href="structvalue.html">value</a>&amp; <a class="code" href="structvalue.html">value</a>::operator[const <span class="keywordtype">char</span>*]    <span class="comment">// returns value at field in struct</span></div><div class="line"><a class="code" href="structvalue.html">value</a>&amp; <a class="code" href="structvalue.html">value</a>::operator[const <span class="keywordtype">wchar_t</span>*] <span class="comment">// returns value at field in struct</span></div></div><!-- fragment --><p>For example, let's take the value <code>v</code> that was assigned the array shown above. We have the following properties of this value:</p>
<div class="fragment"><div class="line">v.is_null() == <span class="keyword">false</span>             <span class="comment">// v is not null</span></div><div class="line">v.is_array() == <span class="keyword">true</span>             <span class="comment">// v is an array</span></div><div class="line">v.size() == 1                    <span class="comment">// v has one element</span></div><div class="line">v.has(1) == <span class="keyword">false</span>                <span class="comment">// v has no array element at index 1</span></div><div class="line">v.nth(-1) == 0                   <span class="comment">// v last element is at index 0</span></div><div class="line">v[0].is_struct() == <span class="keyword">true</span>         <span class="comment">// v[0] is a struct</span></div><div class="line">v[0].has(<span class="stringliteral">&quot;name&quot;</span>) == <span class="keyword">true</span>         <span class="comment">// v[0] has field name &quot;name&quot;</span></div><div class="line">v[0].nth(<span class="stringliteral">&quot;name&quot;</span>) == 0            <span class="comment">// v[0] has field name &quot;name&quot; at index 0</span></div><div class="line">v[0][0].is_string() == <span class="keyword">true</span>      <span class="comment">// v[0][0] == v[0][&quot;name&quot;] is a string</span></div><div class="line">v[0].has(<span class="stringliteral">&quot;toys&quot;</span>) == <span class="keyword">true</span>         <span class="comment">// v[0] has field name &quot;toys&quot;</span></div><div class="line">v[0][<span class="stringliteral">&quot;toys&quot;</span>].is_array() == <span class="keyword">true</span>  <span class="comment">// v[0][&quot;toys&quot;] is an array</span></div><div class="line">v[0][<span class="stringliteral">&quot;toys&quot;</span>].empty() == <span class="keyword">false</span>    <span class="comment">// v[0][&quot;toys&quot;] is not empty</span></div></div><!-- fragment --><p>When accessing structs (JSON objects) by field name, make sure to use existing member field names only. A new member fieldname-value pair is dynamically added to the structure to accomodate the new entry for the field.</p>
<p>Also arrays are extended to accommodate the indexed array element. A negative index accesses elements from the array's end, with index -1 accessing the last value. Also the <code>value::has(int)</code> and <code>value::nth(int)</code> methods take a negative index for bounds checking on arrays and will return <code>false</code> or negative, respectively.</p>
<p>Use <code><a class="el" href="structvalue.html#aa348b92d0343ec28a56542f2c47dc3aa" title="set/allocate size of array ">value::size(int)</a></code> to change array size or set arrays to zero length. Use negative size with <code><a class="el" href="structvalue.html#aa348b92d0343ec28a56542f2c47dc3aa" title="set/allocate size of array ">value::size(int)</a></code> to remove elements from the end.</p>
<p>You may want to use iterators to retrieve data from structs and arrays (see further below).</p>
<p>To retrieve atomic data we can use casts on a value <code>v</code> as follows:</p>
<div class="fragment"><div class="line">(double)v                   <span class="comment">// 64 bit double or 0.0 if not numeric</span></div><div class="line">(<span class="keywordtype">int</span>)v                      <span class="comment">// 32 bit int or 0 if not numeric</span></div><div class="line">(LONG64)v                   <span class="comment">// 64 bit int or 0 if not numeric</span></div><div class="line">(<span class="keywordtype">char</span>*)v                    <span class="comment">// convert to string</span></div><div class="line">(<span class="keywordtype">string</span>)v                   <span class="comment">// convert to std::string</span></div><div class="line">(<span class="keywordtype">wchar_t</span>*)v                 <span class="comment">// convert to wide string</span></div><div class="line">(wstring)v                  <span class="comment">// convert to std::wstring</span></div><div class="line">(<span class="keywordtype">bool</span>)v                     <span class="comment">// same as is_true()</span></div><div class="line">(ULONG64)v                  <span class="comment">// nonzero time_t if v contains an ISO 8601 date time</span></div><div class="line">(<a class="code" href="struct__base64.html">_base64</a>)v                  <span class="comment">// base64 encoding of v</span></div></div><!-- fragment --><p>It is valid to cast a primitive type to any of the other primitive types shown above and no runtime error will occur, although you may loose some information when an atomic value has no representation in the target type's value space. Casting a number to a string is fine, but casting a string to a number only gives a nonzero numeric value if the string is numeric. Casting a value to base64 produces its base64 encoding.</p>
<p>To access base64 binary raw data of a value <code>v</code>, we use the following methods:</p>
<div class="fragment"><div class="line"><a class="code" href="struct__base64.html">_base64</a>&amp; base64 = v;</div><div class="line"><span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *raw = base64.<a class="code" href="struct__base64.html#accb75dbcdaf316a692d92d42783ffcb8">ptr</a>();  <span class="comment">// points to raw binary data</span></div><div class="line"><span class="keywordtype">int</span> size = base64.<a class="code" href="struct__base64.html#a89555bd2f9d977fd17bc2823bef10230">size</a>();           <span class="comment">// that is of this size</span></div></div><!-- fragment --><p>Arrays and structs are compound types that cannot be cast to or from other types (but if you do cast, an empty array or struct is created an no runtime error will occur). So we should check for array and struct types to obtain their content. For example:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (v.is_array())</div><div class="line">{</div><div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; v.size(); ++i)</div><div class="line">  {</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; array_value = v[i];</div><div class="line">    ... <span class="comment">// use and/or set array_value</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>We use the iterators <code><a class="el" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a></code> and <code><a class="el" href="structvalue.html#a34f1b384ded31c97cf40e66aebde8850">value::const_iterator</a></code> to loop over the values in structs and arrays:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (v.is_struct() || v.is_array())</div><div class="line">{</div><div class="line">  <span class="keywordflow">for</span> (<a class="code" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a> i = v.begin(); i != v.end(); ++i)</div><div class="line">  {</div><div class="line">    <span class="keywordtype">int</span> index = i.index();              <span class="comment">// index of element</span></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span> *name = i.name();        <span class="comment">// name() is nonempty for structs</span></div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; element = *i;</div><div class="line">    ... <span class="comment">// use index, name, and/or use/set the element value</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>The iterator method <code>value::iterator::index()</code> returns the integer index of the struct or array element. The <code>value::iterator::name()</code> method returns the name of the struct member, or empty <code>""</code> if the type is not a struct. The <code><a class="el" href="structvalue.html#a34f1b384ded31c97cf40e66aebde8850">value::const_iterator</a></code> does not permit the value referenced by the iterator to be modified.</p>
<p>There are two lower level iterators for structs and arrays, which are slightly more efficient to use compared to the <code><a class="el" href="structvalue.html#aec762fde6750eaaed2cc1c835d38408a">value::iterator</a></code>. These array and struct iterators have an <code>index()</code> method to obtain the index (an int). Struct iterators have a <code>name()</code> method to obtain a member's name (a string).</p>
<p>For example, to traverse a value <code>v</code> that is an array or a struct:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (v.is_array())</div><div class="line">{</div><div class="line">  <a class="code" href="struct__array.html">_array</a>&amp; vec = v;  <span class="comment">// cast to _array</span></div><div class="line">  <span class="keywordflow">for</span> (<a class="code" href="struct__array.html#a61e069daf5d5b31875a5d249216ac8d3">_array::iterator</a> i = vec.<a class="code" href="struct__array.html#acb0f4e1bb00cc556d8fd0e76489e7db3">begin</a>(); i != vec.<a class="code" href="struct__array.html#a6e4804695d0f5ab0e1cae9ea0788f84a">end</a>(); ++i)</div><div class="line">  {</div><div class="line">    <span class="keywordtype">int</span> array_index = i.index();</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; array_value = *i;</div><div class="line">    ... <span class="comment">// use array_index, use and/or set array_value</span></div><div class="line">  }</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (v.is_struct())</div><div class="line">{</div><div class="line">  <a class="code" href="struct__struct.html">_struct</a>&amp; rec = v;  <span class="comment">// cast to _struct</span></div><div class="line">  <span class="keywordflow">for</span> (<a class="code" href="struct__struct.html#a88edf40f7bb954061eddc160b1105ff3">_struct::iterator</a> i = rec.<a class="code" href="struct__struct.html#affe3d3358649a2e72dcdd44bd0060ce8">begin</a>(); i != rec.<a class="code" href="struct__struct.html#a927df1efbfb8f7aabb7417fc971d697e">end</a>(); ++i)</div><div class="line">  {</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span> *member_name = i.name();</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; member_value = *i;</div><div class="line">    ... <span class="comment">// use member_name, use and/or set member_value</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>As usual, the <code><a class="el" href="struct__struct.html#a665a3a79dd4b255a781b140f3739b52c">_struct::const_iterator</a></code> and <code><a class="el" href="struct__array.html#a4eb4cf7bbe96231b59032b424e76555b">_array::const_iterator</a></code> do not permit the values referenced by the iterator to be modified.</p>
<p>XML-RPC parameter lists are similar to arrays and its values are indexed. We can also iterate over response parameters after an XML-RPC REST call:</p>
<div class="fragment"><div class="line"><a class="code" href="structmethod_call.html">methodCall</a> rpc(ctx, <span class="stringliteral">&quot;endpoint URL&quot;</span>, <span class="stringliteral">&quot;methodName&quot;</span>);</div><div class="line"><a class="code" href="structparams.html">params</a> request(ctx, 2);</div><div class="line">request[0] = ...;                <span class="comment">// first request parameter</span></div><div class="line">request[1] = ...;                <span class="comment">// second request parameter</span></div><div class="line"><a class="code" href="structparams.html">params</a> response = rpc(request);  <span class="comment">// execute the call</span></div><div class="line"><span class="keywordflow">if</span> (!rpc.error())</div><div class="line">{</div><div class="line">  <span class="keywordflow">for</span> (<a class="code" href="structparams.html#a42e515c9a4bc03a29382e63dddea8496">params::iterator</a> i = response.<a class="code" href="structparams.html#a338caa1a01c45b5578929775722b08d4">begin</a>(); i != response.<a class="code" href="structparams.html#af4fc372bc47066cd62c6f6424e26e003">end</a>(); ++i)</div><div class="line">  {</div><div class="line">    <span class="keywordtype">int</span> index = i.index();</div><div class="line">    <a class="code" href="structvalue.html">value</a>&amp; param_value = *i;</div><div class="line">    ... <span class="comment">// use param_value of response params</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>We should note that JSON REST does not require parameter types, for example:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><a class="code" href="structvalue.html">value</a> request(ctx);</div><div class="line"><a class="code" href="structvalue.html">value</a> response(ctx);</div><div class="line">request[0] = ...;                <span class="comment">// first request parameter</span></div><div class="line">request[1] = ...;                <span class="comment">// second request parameter</span></div><div class="line"><span class="keywordflow">if</span> (!<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(cts, <span class="stringliteral">&quot;endpoint URL&quot;</span>, request, response))</div><div class="line">{</div><div class="line">  ... <span class="comment">// use response value</span></div><div class="line">}</div></div><!-- fragment --><p>There are two additional methods to invoke on parameters:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> <a class="code" href="structparams.html#a6e150e3958d176f05bd6579d5d14836c">params::size</a>();         <span class="comment">// returns number of parameters</span></div><div class="line"><span class="keywordtype">bool</span> <a class="code" href="structparams.html#af65f66c853166bc136578dffdde31316">params::empty</a>();       <span class="comment">// true if no parameters</span></div></div><!-- fragment --><p>All dynamically allocated memory that is internally used to store data is deallocated with:</p>
<div class="fragment"><div class="line">soap_destroy(ctx);  <span class="comment">// delete all values</span></div><div class="line">soap_end(ctx);      <span class="comment">// delete temp data</span></div><div class="line">soap_free(ctx);     <span class="comment">// delete context allocated with soap_new()</span></div></div><!-- fragment --><p>Additional C++ examples are located in <code>gsoap/samples/xml-rpc-json</code>:</p>
<ul>
<li><code>xml-rpc-currentTime.cpp</code>: XML-RPC C++ client, also uses JSON</li>
<li><code>xml-rpc-currentTimeServer.cpp</code>: XML-RPC C++ server (CGI and multi-threaded stand-alone)</li>
<li><code>xml-rpc-weblogs.cpp</code>: XML-RPC C++ client</li>
<li><code>xml-rpc-json.cpp</code>: XML-RPC to/from JSON example</li>
<li><code>json-currentTime.cpp</code>: JSON REST C++ client</li>
<li><code>json-currentTimeServer.cpp</code>: JSON REST C++ server (CGI and multi-threaded stand-alone)</li>
<li><code>json-GitHub.cpp</code>: JSON REST C++ client for GitHub API v3</li>
</ul>
<h2><a class="anchor" id="cpp-cl"></a>
C++ XML-RPC client example                                             </h2>
<p>A typical XML-RPC calling sequence in C++ is:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span>      <span class="comment">// generated by the command: soapcpp2 -CSL xml-rpc.h</span></div><div class="line"><span class="preprocessor">#include &quot;xml-rpc-io.h&quot;</span> <span class="comment">// to serialize XML-RPC data to streams</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">// no XML namespaces</span></div><div class="line"><span class="comment">// create a context</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING); <span class="comment">// store Unicode in UTF-8 format</span></div><div class="line">ctx-&gt;send_timeout = 10; <span class="comment">// 10 sec, stop if server is not accepting msg</span></div><div class="line">ctx-&gt;recv_timeout = 10; <span class="comment">// 10 sec, stop if server does not respond in time</span></div><div class="line"><span class="comment">// create an XML-RPC method call object</span></div><div class="line"><a class="code" href="structmethod_call.html">methodCall</a> rpc(ctx, <span class="stringliteral">&quot;endpoint URL&quot;</span>, <span class="stringliteral">&quot;methodName&quot;</span>);</div><div class="line"><span class="comment">// populate the parameters</span></div><div class="line">rpc[0] = 123;           <span class="comment">// first parameter is an integer</span></div><div class="line">rpc[1] = <span class="stringliteral">&quot;abc&quot;</span>;         <span class="comment">// second is a string</span></div><div class="line">rpc[2][<span class="stringliteral">&quot;name&quot;</span>] = <span class="stringliteral">&quot;joe&quot;</span>; <span class="comment">// a record, first member &quot;name&quot;</span></div><div class="line">rpc[2][<span class="stringliteral">&quot;age&quot;</span>] = 23;     <span class="comment">// a record, second member &quot;age&quot;</span></div><div class="line">rpc[3][0] = 456.789;    <span class="comment">// an array, first element (a float)</span></div><div class="line">rpc[3][1] = <span class="stringliteral">&quot;widget&quot;</span>;   <span class="comment">// an array, second element (a string)</span></div><div class="line">rpc[3][2] = <span class="keyword">true</span>;       <span class="comment">// an array, third element (a bool)</span></div><div class="line"><span class="comment">// make the XML-RPC call and retrieve response</span></div><div class="line"><a class="code" href="structparams.html">params</a> response = rpc(request);</div><div class="line"><span class="comment">// check result</span></div><div class="line"><span class="keywordflow">if</span> (rpc.error())</div><div class="line">  soap_stream_fault(ctx, std::err);</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response.<a class="code" href="structparams.html#af65f66c853166bc136578dffdde31316">empty</a>())</div><div class="line">  std::cout &lt;&lt; rpc.fault() &lt;&lt; std::endl;</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response.<a class="code" href="structparams.html#a6e150e3958d176f05bd6579d5d14836c">size</a>() &gt; 1)</div><div class="line">  std::cout &lt;&lt; <span class="stringliteral">&quot;More than one response data&quot;</span> &lt;&lt; std::endl;</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>() &amp;&amp; !response[0].<a class="code" href="structparams.html#af65f66c853166bc136578dffdde31316">empty</a>())</div><div class="line">  <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; response[0].<a class="code" href="structparams.html#a6e150e3958d176f05bd6579d5d14836c">size</a>(); i++)</div><div class="line">    ... = response[0][i];</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>())</div><div class="line">{</div><div class="line">  ... = response[0][<span class="stringliteral">&quot;membername1&quot;</span>];</div><div class="line">  ... = response[0][<span class="stringliteral">&quot;membername2&quot;</span>];</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#a99a7e4bbd0637ef4e752896cf299cfb7">is_base64</a>())</div><div class="line">{</div><div class="line">  <a class="code" href="struct__base64.html">_base64</a> base64&amp; = response[0];</div><div class="line">  <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *raw = base64.<a class="code" href="struct__base64.html#accb75dbcdaf316a692d92d42783ffcb8">ptr</a>();</div><div class="line">  <span class="keywordtype">int</span> size = base64.<a class="code" href="struct__base64.html#a89555bd2f9d977fd17bc2823bef10230">size</a>();</div><div class="line">  ... <span class="comment">// use raw[0..size-1] data</span></div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#a641eee093203fbd4a308e92b9eee1238">is_bool</a>())</div><div class="line">{</div><div class="line">  <span class="keywordtype">bool</span> flag = response[0];</div><div class="line">  ... <span class="comment">// use boolean flag</span></div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb">is_int</a>())</div><div class="line">{</div><div class="line">  LONG64 num = response[0];</div><div class="line">  ... <span class="comment">// use integer</span></div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028">is_double</a>())</div><div class="line">{</div><div class="line">  <span class="keywordtype">double</span> num = response[0];</div><div class="line">  ... <span class="comment">// use double float</span></div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>())</div><div class="line">{</div><div class="line">  <span class="keyword">const</span> <span class="keywordtype">char</span> *str = response[0];</div><div class="line">  <span class="comment">// use string, note that also legal is:</span></div><div class="line">  <span class="keyword">const</span> std::string&amp; st = response[0];</div><div class="line">  <span class="comment">// and conversion from UTF-8 to wide string unicode:</span></div><div class="line">  <span class="keyword">const</span> <span class="keywordtype">wchar_t</span> *w = response[0];</div><div class="line">  <span class="keyword">const</span> std::string&amp; ws = response[0];</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response[0].<a class="code" href="xml-rpc_8h.html#a06cf4ad42a3483b8a0da51f77aefa2bd">is_dateTime</a>())</div><div class="line">{</div><div class="line">  time_t t = (ULONG64)response[0];</div><div class="line">  ... <span class="comment">// use time</span></div><div class="line">}</div><div class="line"><span class="comment">// deallocate all</span></div><div class="line">soap_destroy(ctx);</div><div class="line">soap_end(ctx);</div><div class="line">soap_free(ctx);</div></div><!-- fragment --><p>Alternatively, parameters of a <a class="el" href="structmethod_call.html" title="Represents the &lt;methodCall&gt; element with &lt;methodName&gt; and request &lt;params&gt; for remote invocation...">methodCall</a> can be passed with the <a class="el" href="structmethod_call.html" title="Represents the &lt;methodCall&gt; element with &lt;methodName&gt; and request &lt;params&gt; for remote invocation...">methodCall</a> itself as follows:</p>
<div class="fragment"><div class="line"><a class="code" href="structmethod_call.html">methodCall</a> rpc(ctx, <span class="stringliteral">&quot;endpoint URL&quot;</span>, <span class="stringliteral">&quot;methodName&quot;</span>);</div><div class="line"><span class="comment">// create 5 parameters</span></div><div class="line"><a class="code" href="structparams.html">params</a> request(ctx, 5);</div><div class="line"><span class="comment">// populate the parameters</span></div><div class="line">request[0] = 123;           <span class="comment">// first parameter is an integer</span></div><div class="line">request[1] = <span class="stringliteral">&quot;abc&quot;</span>;         <span class="comment">// second is a string</span></div><div class="line">request[2][<span class="stringliteral">&quot;name&quot;</span>] = <span class="stringliteral">&quot;joe&quot;</span>; <span class="comment">// a record, first member &quot;name&quot;</span></div><div class="line">request[2][<span class="stringliteral">&quot;age&quot;</span>] = 23;     <span class="comment">// a record, second member &quot;age&quot;</span></div><div class="line">request[3][0] = 456.789;    <span class="comment">// an array, first element (a float)</span></div><div class="line">request[3][1] = <span class="stringliteral">&quot;widget&quot;</span>;   <span class="comment">// an array, second element (a string)</span></div><div class="line">request[3][2] = <span class="keyword">true</span>;       <span class="comment">// an array, third element (a bool)</span></div><div class="line"><span class="comment">// make the XML-RPC call with request parameters, retrieve response</span></div><div class="line"><a class="code" href="structparams.html">params</a> response = rpc(request);</div></div><!-- fragment --><p>Note that in the client code, after the response is retrieved, the implicit type casts done by assignments will retrieve the values that are type-cast converted if needed. These casts can be used anywhere to retrieve values:</p>
<div class="fragment"><div class="line"><a class="code" href="structparams.html">params</a> response = rpc();</div><div class="line"><span class="keywordtype">double</span> sum = 0.0;</div><div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; response.<a class="code" href="structparams.html#a6e150e3958d176f05bd6579d5d14836c">size</a>(); i++)</div><div class="line">  <span class="keywordflow">if</span> (response[i].<a class="code" href="xml-rpc_8h.html#a26f8409f8dd1b093bea7dbd036392be0">is_number</a>())    <span class="comment">// is this parameter an int or float?</span></div><div class="line">    sum += (<span class="keywordtype">double</span>)response[i];</div></div><!-- fragment --><p>Type casts can also be used to convert data, which means they never produce an exception. Casting to string <code>(const char*)</code> converts atomic values to strings, but does not convert compound types such as arrays and structs.</p>
<div class="fragment"><div class="line"><a class="code" href="structparams.html">params</a> response = rpc();</div><div class="line"><span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; response.<a class="code" href="structparams.html#a6e150e3958d176f05bd6579d5d14836c">size</a>(); i++)</div><div class="line">  printf(<span class="stringliteral">&quot;response[%d] = %s\n&quot;</span>, i, (<span class="keyword">const</span> <span class="keywordtype">char</span>*)response[i]);</div></div><!-- fragment --><p>which prints a string representation of the int, double, boolean, time, or base64 values of parameters. An empty string is printed for arrays and structs. Use iterators to walk over arrays and structs to print values. Or use the JSON API <code><a class="el" href="json_8h.html">json.h</a></code> and <code>json.cpp</code> to print values in JSON format, see further on JSON below.</p>
<h2><a class="anchor" id="cpp-sr"></a>
C++ XML-RPC server example                                             </h2>
<p>A typical C++ XML-RPC server sequence is:</p>
<div class="fragment"><div class="line"><span class="comment">// create an allocation context</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING);</div><div class="line"><span class="comment">// create an XML-RPC methodCall object</span></div><div class="line"><a class="code" href="structmethod_call.html">methodCall</a> rpc(ctx);</div><div class="line"><span class="comment">// Option 1: parse and write to/from stdin/out for CGI</span></div><div class="line"><span class="comment">// (no code needed)</span></div><div class="line"><span class="comment">// Option 2: parse and write to/from FILE or socket</span></div><div class="line"><span class="comment">// ctx-&gt;recvfd = ...; // set input file descriptor</span></div><div class="line"><span class="comment">// ctx-&gt;sendfd = ...; // set output file descriptor</span></div><div class="line"><span class="comment">// Option 3: parse and write to/from IO streams</span></div><div class="line"><span class="comment">// ctx-&gt;is = ...; // set input stream</span></div><div class="line"><span class="comment">// ctx-&gt;os = ...; // set output stream</span></div><div class="line"><span class="keywordflow">if</span> (rpc.recv() != SOAP_OK)</div><div class="line">  soap_print_fault(ctx, stderr);</div><div class="line"><span class="keywordflow">else</span></div><div class="line">{</div><div class="line">  <span class="comment">// create response</span></div><div class="line">  <a class="code" href="structmethod_response.html">methodResponse</a> response(ctx);</div><div class="line">  <span class="comment">// check method name</span></div><div class="line">  <span class="keywordflow">if</span> (!strcmp(rpc.name(), <span class="stringliteral">&quot;methodName&quot;</span>))</div><div class="line">  {</div><div class="line">    <span class="comment">// method name matches: populate response parameters with values:</span></div><div class="line">    response[0] = ...;</div><div class="line">    response[1] = ...;</div><div class="line">    ... <span class="comment">// add response data </span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span></div><div class="line">  {</div><div class="line">    <span class="comment">// otherwise, set fault</span></div><div class="line">    response.set_fault(<span class="stringliteral">&quot;Wrong method&quot;</span>);</div><div class="line">  }</div><div class="line">  <span class="comment">// send response</span></div><div class="line">  <span class="keywordflow">if</span> (response.send() != SOAP_OK)</div><div class="line">    soap_print_fault(ctx, stderr);</div><div class="line">}</div><div class="line"><span class="comment">// close (but keep-alive setting keeps socket open)</span></div><div class="line">soap_closesock(ctx);</div><div class="line"><span class="comment">// clean up</span></div><div class="line">soap_destroy(ctx);</div><div class="line">soap_end(ctx);</div><div class="line">soap_free(ctx);</div></div><!-- fragment --><p>With option 1 the server code above uses standard in/out and thus runs over CGI. Other possibilities are given by options 2 and 3.</p>
<p>To serve requests at a port, we use the <code>soap_bind()</code> and <code>soap_accept()</code> calls to bind the server to a port and accept requests via socket, see also the docs and examples for these calls (see for example <code>gsoap/samples/webserver.c</code>):</p>
<div class="fragment"><div class="line"><span class="comment">// create an allocation context</span></div><div class="line">soap *ctx = soap_new1(SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);</div><div class="line"><span class="comment">// bind to port 8080</span></div><div class="line"><span class="keywordflow">if</span> (!soap_valid_socket(soap_bind(ctx, NULL, 8080, 100)))</div><div class="line">  ... <span class="comment">// error, stop</span></div><div class="line"><span class="comment">// accept messages in server loop</span></div><div class="line"><span class="keywordflow">for</span> (;;)</div><div class="line">{</div><div class="line">  <span class="keywordflow">if</span> (!soap_valid_socket(soap_accept(ctx)))</div><div class="line">    ... <span class="comment">// error, stop</span></div><div class="line">  <span class="comment">// create a method object</span></div><div class="line">  <a class="code" href="structmethod_call.html">methodCall</a> rpc(ctx);</div><div class="line">  <span class="comment">// parse it from socket</span></div><div class="line">  <span class="keywordflow">if</span> (rpc.recv() != SOAP_OK)</div><div class="line">    soap_print_fault(ctx, stderr);</div><div class="line">  ... <span class="comment">// process request, produce result to send as shown above</span></div><div class="line">  <span class="comment">// close (but keep-alive setting keeps socket open)</span></div><div class="line">  soap_closesock(ctx);</div><div class="line">  <span class="comment">// clean up</span></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">}</div><div class="line"><span class="comment">// free context</span></div><div class="line">soap_free(ctx);</div></div><!-- fragment --><h2><a class="anchor" id="cpp-io"></a>
C++ XML-RPC serialization from/to streams                              </h2>
<p>To send and receive XML over streams, use <code>xml-rpc-io.h</code> and <code>xml-rpc-io.cpp</code>. For example:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;xml-rpc-io.h&quot;</span></div><div class="line">std::cout &lt;&lt; response[0] &lt;&lt; std::endl;</div></div><!-- fragment --><p>which will display the data in XML-RPC format. To parse XML-RPC data from a stream, use:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;xml-rpc-io.h&quot;</span></div><div class="line"><a class="code" href="structvalue.html">value</a> v(ctx);</div><div class="line">std::cin &gt;&gt; v;</div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ... <span class="comment">// check for parse errors (can also use v.soap-&gt;error)</span></div></div><!-- fragment --><p>Compile and link together with <code>soapC.cpp</code>, <code>xml-rpc.cpp</code>, <code>xml-rpc-io.cpp</code>, and <code>stdsoap2.cpp</code>.</p>
<h2><a class="anchor" id="cpp-js"></a>
C++ JSON serialization from/to streams                                 </h2>
<p>To display values in JSON format or to parse JSON data, use the <code><a class="el" href="json_8h.html">json.h</a></code> and <code>json.cpp</code> JSON serializers in combination with <code>xml-rpc.cpp</code> and the auto-generated <code>soapH.h</code> and <code>soapC.cpp</code>. It is also possible to send and receive JSON data over HTTP as JSON REST operations, but this requires some more coding (see <a class="el" href="index.html#cpp-jr">C++ JSON REST clients and servers </a> below).</p>
<p>Because the internal data is the same for XML-RPC and JSON, You can write data in XML-RPC or in JSON format. You can also parse XML-RPC data and write to JSON data and vice versa.</p>
<p>To write JSON to a stream you can use the <code>&lt;&lt;</code> operator on an output stream and a JSON value.</p>
<p>To parse JSON from a stream you can use the <code>&gt;&gt;</code> operator on an input stream and populate a JSON value.</p>
<p>For example, you can parse a JSON-formatted string and use that data to make an XML-RPC call. The result of the call is displayed in JSON, nicely indented using the <code>SOAP_XML_INDENT</code> flag (this XML indent flag also works for JSON):</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &lt;sstream&gt;</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">// no XML namespaces</span></div><div class="line"></div><div class="line"><span class="comment">// SOAP_C_UTFSTRING: UTF-8 content in char*, SOAP_XML_INDENT: indent JSON</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><a class="code" href="structvalue.html">value</a> request(ctx);</div><div class="line">std::istringstream in;</div><div class="line">in.str(<span class="stringliteral">&quot;[ [1, \&quot;2\&quot;, 3.14, true], {\&quot;name\&quot;: \&quot;john\&quot;, \&quot;age\&quot;: 24} ]&quot;</span>);</div><div class="line">in &gt;&gt; request;                      <span class="comment">// parse JSON, store as XML-PRC data</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...                 <span class="comment">// check for parse errors</span></div><div class="line"><a class="code" href="structparams.html">params</a> response = rpc(request);     <span class="comment">// make the XML-RPC call</span></div><div class="line">std::cout &lt;&lt; response &lt;&lt; std::endl; <span class="comment">// display result in JSON (indented)</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...                 <span class="comment">// check for write errors</span></div></div><!-- fragment --><p>To force reading and writing JSON in ISO 8859-1 format, use the <code>SOAP_ENC_LATIN</code> flag to set the context (not recommended).</p>
<p>Optionally use <code>SOAP_XML_INDENT</code> to indent XML and JSON.</p>
<p>To parse JSON values from a file or any other non-HTTP source, it is recommended to set the <code>SOAP_ENC_PLAIN</code> context flag to prevent the parser from attempting to read a MIME or HTTP headers (HTTP headers are required with JSON-RPC):</p>
<div class="fragment"><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT | SOAP_ENC_PLAIN);</div><div class="line"><a class="code" href="structvalue.html">value</a> v(ctx);</div><div class="line">in &gt;&gt; v;       <span class="comment">// SOAP_ENC_PLAIN: read JSON without parsing MIME/HTTP header</span></div></div><!-- fragment --><p>Compile and link your code together with <code>soapC.cpp</code> (generated), <code>xml-rpc.cpp</code>, <code>json.cpp</code>, and <code>stdsoap2.cpp</code>.</p>
<p>The JSON protocol has fewer data types than XML-RPC, so type information can be lost when serializing to JSON:</p>
<ul>
<li>XML-RPC uses a base64 type to exchange raw binary data. The base64 data is converted to a string with base64 content by the JSON serializer. See also <a class="el" href="index.html#base64">JSON and base64 </a>.</li>
<li>XML-RPC has a dateTime type, JSON does not. The JSON serializer converts the dateTime type to a dateTime-formatted string. See also <a class="el" href="index.html#dateTime">JSON and ISO 8601 dateTime </a>.</li>
</ul>
<p>See the section on C++ examples on how to populate and retrieve C++ data.</p>
<p>Strings are stored and exchanged in UTF-8 format in 8-bit strings (<code>char*</code> and <code>std::string</code>) by using the <code>SOAP_C_UTFSTRING</code> flag. Wide strings (i.e. <code>wchar_t*</code> and <code>std::wstring</code> ) are converted to UTF-8.</p>
<h2><a class="anchor" id="cpp-jr"></a>
C++ JSON REST clients and servers                                      </h2>
<p>To use JSON REST on the client side, we use <code>json_call</code>:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span>            <span class="comment">// also compile and link json.cpp</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">// no XML namespaces</span></div><div class="line"></div><div class="line"><span class="comment">// SOAP_C_UTFSTRING: UTF-8 content in char*, SOAP_XML_INDENT: indent JSON</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><a class="code" href="structvalue.html">value</a> request(ctx), response(ctx);</div><div class="line">... <span class="comment">// now populate the request data to send</span></div><div class="line"></div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(ctx, <span class="stringliteral">&quot;URL&quot;</span>, &amp;request, &amp;response) != SOAP_OK)) <span class="comment">// POST</span></div><div class="line">  ... <span class="comment">// error</span></div><div class="line"><span class="keywordflow">else</span></div><div class="line">  ... <span class="comment">// use the response data</span></div><div class="line">... <span class="comment">// make other calls etc.</span></div><div class="line">soap_destroy(ctx); <span class="comment">// delete all values</span></div><div class="line">soap_end(ctx);</div><div class="line">... <span class="comment">// make other calls etc.</span></div><div class="line">soap_free(ctx);    <span class="comment">// free context</span></div></div><!-- fragment --><p>A <code>json_call</code> takes a context, an endpoint URL (with URL query string parameters as needed), and optional <code>in</code> and <code>out</code> values to send and receive, respectively. This function returns <code>SOAP_OK</code> (zero) for success or <code>EOF</code>, <code>SOAP_SYNTAX_ERROR</code>, or an HTTP error code.</p>
<p>To use the HTTP POST method, pass both <code>in</code> and <code>out</code> values to <code>json_call</code>. For the GET method, pass a NULL to <code>in</code>. For the PUT method, pass a NULL to <code>out</code>. For the DELETE method, pass both NULL to <code>in</code> and <code>out</code>.</p>
<p>Besides <code>json_call</code>, there are other JSON API functions:</p>
<ul>
<li><code>int json_call(soap *ctx, const char *URL, value *in, value *out)</code> makes a POST, GET, PUT, DELETE call, returns <code>SOAP_OK</code> or error code. POST method: pass both <code>in</code> and <code>out</code>. GET method: pass a NULL to <code>in</code>. PUT method: pass a NULL to <code>out</code>. DELETE method: pass both NULL to <code>in</code> and <code>out</code>. <code>SOAP_OK</code> is returned for POST and GET methods upon success. An HTTP status code of 200 (OK) or 202 (Accepted) is returned for PUT and DELETE methods upon success.</li>
<li><code>int json_write(soap *ctx, const value *v)</code> writes JSON value to current file, socket, or stream. Returns <code>SOAP_OK</code> or error. Set file/socket file descriptor to write to with <code>ctx-&gt;sendfd = fd</code> (1 by default). In C++, set output stream with <code>ctx-&gt;os = ostream</code> to write to.</li>
<li><code>int <a class="el" href="json_8h.html#a927016fe60cb59422e4769dd7803462c" title="Read JSON value from context&#39;s input (socket, stream, FILE, or string) ">json_read(soap *ctx, value *v)</a></code> reads JSON value from current file, socket, or stream. Returns <code>SOAP_OK</code> or error. Set file/socket file descriptor with <code>ctx-&gt;recvfd = fd</code> to read from (0 by default). In C++, set input stream with <code>ctx-&gt;is = istream</code>.</li>
</ul>
<p>The are two other lower-level functions <code>json_send</code> and <code>json_recv</code> that are similar to <code>json_write</code> and <code>json_read</code> but do not initialize the sending and receiving operations and do not flush after the sending and receiving operations.</p>
<p>To implement a JSON REST server for CGI (e.g. install in cgi-bin):</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span>            <span class="comment">// also compile and link json.cpp</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">// no XML namespaces</span></div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main()</div><div class="line">{</div><div class="line">  soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT | SOAP_ENC_PLAIN);</div><div class="line">  <a class="code" href="structvalue.html">value</a> request(ctx), response(ctx);</div><div class="line">  <span class="keywordflow">if</span> (soap_begin_recv(ctx)</div><div class="line">   || <a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request)</div><div class="line">   || soap_end_recv(ctx))</div><div class="line">  {</div><div class="line">    <a class="code" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01">json_send_fault</a>(ctx); <span class="comment">// return a JSON-formatted fault</span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span></div><div class="line">  {</div><div class="line">    ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">    ... <span class="comment">// set the &#39;response&#39; value</span></div><div class="line">    <span class="comment">// set http content type</span></div><div class="line">    ctx-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line">    <span class="comment">// send http header 200 OK and JSON response</span></div><div class="line">    <span class="keywordflow">if</span> (soap_response(ctx, SOAP_FILE)</div><div class="line">     || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(ctx, response)</div><div class="line">     || soap_end_send(ctx))</div><div class="line">      soap_closesock(ctx);</div><div class="line">  }</div><div class="line">  <span class="comment">// dealloc all</span></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>The above server works with CGI, which is rather slow and stateless. A stand-alone JSON REST server is recommended. You can also use the Apache and IIS plugins for gSOAP to deploy JSON REST services. See the <a href="https://www.genivia.com/docs.html">documentation</a>.</p>
<p>Note that we use <code><a class="el" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01" title="Respond with a JSON error when an internal fault occurred (i.e. soap-&gt;error is nonzero), as per Google JSON Style Guide. ">json_send_fault()</a></code> instead of <code>soap_send_fault()</code> when an internal error occurred, since we want the error to be reported in JSON format as per Google JSON Style Guide. For application-specific errors, we use <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> as follows:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (some application error occurred)</div><div class="line">  <a class="code" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0">json_send_error</a>(ctx, 400, <span class="stringliteral">&quot;Error message&quot;</span>, <span class="stringliteral">&quot;Error details&quot;</span>);</div><div class="line"><span class="keywordflow">else</span></div><div class="line">  ... <span class="comment">// send the response</span></div></div><!-- fragment --><p>You can specify an HTTP error code such as 400 in this case, which means that a HTTP 400 Bad Request is returned to the client.</p>
<p>The <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> function is a convenient shortcut to return an error message with an HTTP error code. To return a JSON response with a HTTP error code use the following:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> status = 400; <span class="comment">// HTTP 400 Bad Request</span></div><div class="line">soap-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line"><span class="keywordflow">if</span> (soap_response(soap, SOAP_FILE + status)</div><div class="line"> || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(soap, v)</div><div class="line"> || soap_end_send(soap))</div><div class="line">  soap_closesock(soap);</div></div><!-- fragment --><p>The code for a stand-alone server is the same, except that we call <code>soap_bind()</code> and <code>soap_accept()</code> to serve requests on a port. Here is a simple iterative server serving requests on port 8080:</p>
<div class="fragment"><div class="line"><span class="comment">// create an allocation context</span></div><div class="line">soap *ctx = soap_new1(SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);</div><div class="line"><span class="comment">// bind to port 8080</span></div><div class="line"><span class="keywordflow">if</span> (!soap_valid_socket(soap_bind(ctx, NULL, 8080, 100)))</div><div class="line">  ... <span class="comment">// error, stop</span></div><div class="line"><span class="comment">// accept messages in server loop</span></div><div class="line"><span class="keywordflow">for</span> (;;)</div><div class="line">{</div><div class="line">  <span class="keywordflow">if</span> (!soap_valid_socket(soap_accept(ctx)))</div><div class="line">    ... <span class="comment">// error, stop</span></div><div class="line">  <a class="code" href="structvalue.html">value</a> request(ctx), response(ctx);</div><div class="line">  <span class="keywordflow">if</span> (soap_begin_recv(ctx)</div><div class="line">   || <a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request)</div><div class="line">   || soap_end_recv(ctx))</div><div class="line">  {</div><div class="line">    <a class="code" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01">json_send_fault</a>(ctx); <span class="comment">// return a JSON-formatted fault</span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span></div><div class="line">  {</div><div class="line">    ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">    ... <span class="comment">// set the &#39;response&#39; value</span></div><div class="line">    <span class="comment">// set http content type</span></div><div class="line">    ctx-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line">    <span class="comment">// send http header 200 OK and JSON response</span></div><div class="line">    <span class="keywordflow">if</span> (soap_response(ctx, SOAP_FILE)</div><div class="line">     || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(ctx, response)</div><div class="line">     || soap_end_send(ctx))</div><div class="line">      soap_closesock(ctx);</div><div class="line">  }</div><div class="line">  <span class="comment">// dealloc all</span></div><div class="line">  soap_destroy(ctx);</div><div class="line">  soap_end(ctx);</div><div class="line">}</div><div class="line">soap_free(ctx);</div></div><!-- fragment --><p>Note that <code>SOAP_ENC_PLAIN</code> should be used with CGI, since we are reading from a non-HTTP source with CGI. We do not use this flag with gSOAP stand-alone servers. Iterative stand-alone services are not performant and may block requests. We recommend stand-alone multi-threaded services.</p>
<p>Compile and link your code together with <code>soapC.cpp</code> (generated with <code>soapcpp2 -CSL <a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>), <code>xml-rpc.cpp</code>, <code>json.cpp</code>, and <code>stdsoap2.cpp</code>.</p>
<p>For C++ client and server examples, please see the gSOAP package content <code>gsoap/samples/xml-rpc-json</code>:</p>
<ul>
<li><code>json-currentTime.cpp</code>: JSON REST C++ client</li>
<li><code>json-currentTimeServer.cpp</code>: JSON REST C++ server (CGI and multi-threaded stand-alone)</li>
</ul>
<p>The presentation in this section concerned stand-alone JSON REST services. To combine SOAP/XML with JSON REST services, see <a class="el" href="index.html#soap">Serving JSON and SOAP requests on the same server port </a> for details.</p>
<h2><a class="anchor" id="cpp-rpc"></a>
C++ JSON-RPC clients and servers                                      </h2>
<p>The <a href="http://json-rpc.org/wiki/specification">JSON-RPC 1.0 specification</a> (the "original version") adds <code>method</code>, <code>parameter</code> and <code>id</code> fields to the request message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;method&quot;: &quot;echo&quot;,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;params&quot;: [ &quot;Hello World!&quot; ],</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>where:</p>
<ul>
<li><code>method</code> is a string with the name of the method to be invoked.</li>
<li><code>params</code> is an array of objects to be passed as parameters to the defined method.</li>
<li><code>id</code> is a value of any type, which is used to match the response with the request that it is replying to.</li>
</ul>
<p>A response message has a <code>result</code> field, an <code>error</code> field, and an <code>id</code>:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;result&quot;: &quot;Welcome!&quot;,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;error&quot;: null,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>where:</p>
<ul>
<li><code>result</code> is the data returned by the invoked method. If an error occurred while invoking the method, this value must be null.</li>
<li><code>error</code> is a specified error code if there was an error invoking the method, otherwise null.</li>
<li><code>id</code> is the id of the request it is responding to.</li>
</ul>
<p>The <a href="http://www.jsonrpc.org/specification">JSON-RPC 2.0 specification</a> makes all 1.0 fields REQUIRED, except for <code>error</code> which MUST NOT be present if there was no error triggered during invocation. The 2.0 specification adds a <code>jsonrpc</code> field in the request message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;jsonrpc&quot;: 2.0,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;method&quot;: &quot;echo&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;params&quot;: [ &quot;Hello World!&quot; ],</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00006"></a><span class="lineno">    6</span>&#160;}</div></div><!-- fragment --> </div><p>and also adds the <code>jsonrpc</code> field to the response message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;jsonrpc&quot;: 2.0,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;result&quot;: &quot;Welcome!&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>The C++ operations are straightforward to conform to the JSON-RPC 1.0 or 2.0 specifications. The example JSON-RPC 2.0 request message shown above is created by the following code that uses <code><a class="el" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call()</a></code> to invoke a JSON-RPC service:</p>
<div class="fragment"><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *endpoint = <span class="stringliteral">&quot;http://...&quot;</span>;</div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"></div><div class="line"><a class="code" href="structvalue.html">value</a> req(ctx), res(ctx);</div><div class="line">req[<span class="stringliteral">&quot;jsonrpc&quot;</span>]   = 2.0;</div><div class="line">req[<span class="stringliteral">&quot;method&quot;</span>]    = <span class="stringliteral">&quot;echo&quot;</span>;</div><div class="line">req[<span class="stringliteral">&quot;params&quot;</span>][0] = <span class="stringliteral">&quot;Hello World!&quot;</span>;</div><div class="line">req[<span class="stringliteral">&quot;id&quot;</span>]        = 1;</div><div class="line"></div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(ctx, endpoint, req, res))               <span class="comment">// JSON-RPC call</span></div><div class="line">  soap_stream_fault(ctx, std::cerr);</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (res.has(<span class="stringliteral">&quot;error&quot;</span>) &amp;&amp; !res[<span class="stringliteral">&quot;error&quot;</span>].is_null()) <span class="comment">// JSON-RPC error?</span></div><div class="line">  std::cerr &lt;&lt; res[<span class="stringliteral">&quot;error&quot;</span>];</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> ((<span class="keywordtype">int</span>)res[<span class="stringliteral">&quot;id&quot;</span>] != 1)                         <span class="comment">// matching id field?</span></div><div class="line">  std::cerr &lt;&lt; <span class="stringliteral">&quot;response id != request id\n&quot;</span>;</div><div class="line"><span class="keywordflow">else</span>                                                  <span class="comment">// all OK!</span></div><div class="line">  std::cout &lt;&lt; res[<span class="stringliteral">&quot;result&quot;</span>];                         <span class="comment">// display result</span></div></div><!-- fragment --><p>For HTTPS use an https endpoint URL. You can control the HTTPS context as explained in the <a href="http://www.genivia.com/tutorials.html">tutorials.</a></p>
<p>The server-side creates response messages similar to the example shown above. To implement a C++ JSON-RPC and JSON REST server, please see the example <code>json-currentTimeServer.cpp</code> located in <code>gsoap/samples/xml-rpc-json</code> in the gSOAP package.</p>
<h2><a class="anchor" id="cpp-raw"></a>
Embedding and serializing raw JSON data as a JSON value in C++        </h2>
<p>A JSON value represented by a <code>value</code> may contain raw JSON data as a string to serialize literally in the output. Deserializing JSON into a JSON <code>value</code> never populates this string, so this feature is to augment JSON output with embedded raw JSON data only.</p>
<p>To add raw JSON data create a <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a></code> object and assign it to a <code>value</code>:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">json::value v(ctx);</div><div class="line"></div><div class="line"><span class="comment">// create a blob of raw JSON</span></div><div class="line"><a class="code" href="struct__rawdata.html">_rawdata</a> blob(ctx, <span class="stringliteral">&quot;[ true, 123, { \&quot;key\&quot;: 456 } ]&quot;</span>);</div><div class="line">v = blob;</div></div><!-- fragment --><p>The <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a> blob</code> can be assigned anywhere where a <code>value</code> is expected, i.e. as an item of an array or as a value property of a JSON object.</p>
<p>To check that a <code>value</code> contains a <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a></code> value and to retrieve it as raw data:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">json::value v(ctx);</div><div class="line"></div><div class="line">...</div><div class="line">if (v.is_rawdata())</div><div class="line">{</div><div class="line">  <a class="code" href="struct__rawdata.html">_rawdata</a> blob = (<a class="code" href="struct__rawdata.html">_rawdata</a>)v;</div><div class="line">  <span class="keywordtype">size_t</span> size = blob.<a class="code" href="struct__rawdata.html#af98f8e8ad4b056cfd2384c85103e2d0c">size</a>();</div><div class="line">  <span class="keywordtype">char</span> *<a class="code" href="structdata.html">data</a> = blob.<a class="code" href="struct__rawdata.html#a9ee0f6fde90e20379c4414f6f95ba819">ptr</a>();</div><div class="line">  ...</div><div class="line">}</div></div><!-- fragment --><p>If the raw data blob does not contain <code>\0</code> bytes, then it is simpler to cast the <code>value</code> to a string:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">json::value v(ctx);</div><div class="line"></div><div class="line">...</div><div class="line">if (v.is_rawdata())</div><div class="line">{</div><div class="line">  <span class="keywordtype">char</span> *data = v;</div><div class="line">  ...</div><div class="line">}</div></div><!-- fragment --><h2><a class="anchor" id="json-ns"></a>
Moving JSON types and operations into a C++ namespace                 </h2>
<p>A C++ namespace is preferred to separate JSON types and operations from other project-related types and operations. This allows you to cleanly compile the JSON API files together with other gSOAP XML data binding files.</p>
<p>To put all JSON (and the internal XML-RPC) types and operations in a <code>json</code> C++ namespace, execute the following commands: </p><pre class="fragment">soapcpp2 -qjson -CSL xml-rpc.h
soapcpp2 -penv -CSL env.h
</pre><p>where <code>env.h</code> is an empty file. This generates <code>jsonStub.h</code> and <code>jsonH.h</code> and two more files <code>jsonC.cpp</code> and <code>envC.cpp</code> to compile with <code>xml-rpc.cpp</code>, <code>json.cpp</code>, and <code>stdsoap2.cpp</code>.</p>
<p>When combining JSON with a wsdl2h-generated header file that declares an XML data binding interface, use this header file instead of an empty <code>env.h</code>. Use soapcpp2 to generate the data binding and client/server code as usual (without option <code>-penv</code>).</p>
<p>Compile the source files together with <code>xml-rpc.cpp</code> and <code>json.cpp</code> and set the macro <code>-DJSON_NAMESPACE</code>, for example: </p><pre class="fragment">c++ -DJSON_NAMESPACE xml-rpc.cpp json.cpp jsonC.cpp envC.cpp stdsoap2.cpp ...
</pre><p>To enable OpenSSL for HTTPS also use <code>-DWITH_OPENSSL</code> to compile. Then link with <code>-lssl</code> and <code>-lcrypto</code>.</p>
<p>Your project should now use the <code>json</code> namespace with the <code>value</code> type, for example:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line">soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">json::value v(ctx);</div><div class="line">std::cin &gt;&gt; v;        <span class="comment">// parse JSON</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...   <span class="comment">// check for errors (can also check v.soap-&gt;error)</span></div><div class="line">std::cout &lt;&lt; v;       <span class="comment">// output JSON</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...   <span class="comment">// check for errors (can also check v.soap-&gt;error)</span></div></div><!-- fragment --><h1><a class="anchor" id="c"></a>
C XML-RPC and JSON                                                          </h1>
<p>With the release of gSOAP 2.8.26, the XML-RPC and JSON C APIs have been greatly improved. The material in this section pertains to gSOAP 2.8.26 and later.</p>
<p>The new C API for XML-RPC and JSON makes it much easier to populate and retrieve data, but not as simple and easy as the C++ API.</p>
<h2><a class="anchor" id="c-files"></a>
List of files                                                         </h2>
<p>The following files define XML-RPC operations and data types:</p>
<ul>
<li><code>xml-rpc.c</code>: XML-RPC C API</li>
<li><code><a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>: XML-RPC data binding as a gSOAP .h file for soapcpp2 (do not #include this file in your project builds)</li>
</ul>
<p>In addition to the files above, for JSON we also need the following files:</p>
<ul>
<li><code><a class="el" href="json_8h.html">json.h</a></code>: JSON C API and JSON serialization</li>
<li><code>json.c</code>: JSON C API and JSON serialization</li>
</ul>
<p>The gSOAP header file <code><a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code> defines all XML-RPC and JSON types and the C API functions to create XML-RPC and JSON data for REST messages.</p>
<p>A note about the following auto-generated files: <code>soapH.h</code>, <code>soapStub.h</code> and <code>soapC.c</code>: these are required for XML-RPC and JSON. To auto-generate these files, execute: </p><pre class="fragment">soapcpp2 -c -CSL xml-rpc.h
</pre><p>Then compile and link the <code>.c</code> files listed above for XML-RPC and JSON with the auto-generated <code>soapC.c</code> and <code>stdsoap2.c</code>: </p><pre class="fragment">cc -I../.. -o myapp myapp.c json.c xml-rpc.c soapC.c ../../stdsoap2.c
</pre><p>Instead of <code>stdsoap2.c</code> you can link <code>libgsoap.a</code> with <code>-lgsoap</code>, when installed by the gSOAP package.</p>
<p>To enable OpenSSL for HTTPS compile with <code>-DWITH_OPENSSL</code> and link <code>-lssl</code>, and <code>-lcrypto</code>: </p><pre class="fragment">cc -DWITH_OPENSSL -I../.. -o myapp myapp.c json.c xml-rpc.c soapC.c ../../stdsoap2.c -lssl -lcrypto
</pre><p>For OpenSSL support, instead of <code>stdsoap2.c</code> you can link <code>libgsoapssl.a</code> with <code>-lgsoapssl</code>, when installed by the gSOAP package.</p>
<p>Because XML namespaces are not used, we can either use <code>-DWITH_NONAMESPACES</code> to compile <code>stdsoap2.c</code> without complaining about a missing global <code>Namespace</code>, or we can define an empty namespaces table somewhere in our code:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}};</div></div><!-- fragment --><h2><a class="anchor" id="c-ex"></a>
Overview                                                                 </h2>
<p>An XML-RPC/JSON data value is created in C as follows, which requires a context <code>ctx</code> with the engine state (the soap struct). The context manages the memory that is internally allocated to hold values.</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span></div><div class="line"></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING);  <span class="comment">/* new context */</span></div><div class="line"></div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"></div><div class="line">soap_end(ctx);      <span class="comment">/* delete all values */</span></div><div class="line">soap_free(ctx);     <span class="comment">/* free context */</span></div></div><!-- fragment --><p>Note that <code>soapH.h</code> is an auto-generated file (see previous section). This file needs to be generated only once and for all. It also references <code>stdsoap2.h</code> and the auto-generated <code>soapStub.h</code>. Compile and link your code with <code>stdsoap2.cpp</code> and the auto-generated <code>soapC.cpp</code> XML-RPC serializers. Also compile and link <code>xml-rpc.cpp</code>. For JSON, compile and link <code>json.cpp</code>.</p>
<p>With the C API, allocating a context and values on the heap may return NULL when your system runs out of memory. On most systems this is unlikely to happen, but to safeguard your code check for NULL returns as follows:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span></div><div class="line"></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING);  <span class="comment">/* new context */</span></div><div class="line"><span class="keywordflow">if</span> (ctx == NULL)</div><div class="line">  ...               <span class="comment">/* out-of-memory error */</span></div><div class="line"></div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keywordflow">if</span> (v == NULL)</div><div class="line">  ...               <span class="comment">/* out-of-memory error */</span></div><div class="line"></div><div class="line">soap_end(ctx);      <span class="comment">/* delete all values */</span></div><div class="line">soap_free(ctx);     <span class="comment">/* free context */</span></div></div><!-- fragment --><p>Also, when enlarging structs and arrays by indexing them beyond their current content, the enlargement may fail and a NULL pointer is returned.</p>
<p>You can use wide strings with Unicode stored in UTF-8-formattted 8-bit <code>char</code> strings. For compatibility with XML-RPC serialization of UTF-8-encoded strings, we MUST use the <code>SOAP_C_UTFSTRING</code> flag to initialize the context with <code>soap_new1(SOAP_C_UTFSTRING)</code>.</p>
<p>The code shown above creates an empty value <code>v</code>. Values can be assigned any one of the following data types:</p>
<div class="fragment"><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(v) = 12345LL;    <span class="comment">/* 64 bit int */</span></div><div class="line"></div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(v) = 12.34;   <span class="comment">/* double float */</span></div><div class="line"></div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(v) = <span class="stringliteral">&quot;abc&quot;</span>;   <span class="comment">/* string */</span></div><div class="line"></div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(v) = soap_wchar2s(ctx, L<span class="stringliteral">&quot;xyz&quot;</span>);</div><div class="line">                         <span class="comment">/* wide string (converted to UTF-8) */</span></div><div class="line"></div><div class="line">*<a class="code" href="xml-rpc_8h.html#a1f8f465811b8a8a5f2c186c52273399a">bool_of</a>(v) = 0;         <span class="comment">/* Boolean false (0) or true (1) */</span></div><div class="line"></div><div class="line">*<a class="code" href="xml-rpc_8h.html#ad4147857ac2f220b7eae794d66f18810">dateTime_of</a>(v) = soap_dateTime2s(ctx, time(0));</div><div class="line">                         <span class="comment">/* time_t value serialized as ISO 8601 date time */</span></div><div class="line"></div><div class="line"><span class="comment">/* create an array [24, 99.99, &quot;abc&quot;] */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0)) = 24;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 1)) = 99.99;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 2)) = <span class="stringliteral">&quot;abc&quot;</span>;</div><div class="line"></div><div class="line"><span class="comment">/* create a struct (JSON object) {&quot;name&quot;: &quot;gsoap&quot;, &quot;major&quot;: 2.8, &quot;©&quot;: 2015} */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(v, <span class="stringliteral">&quot;name&quot;</span>)) = <span class="stringliteral">&quot;gsoap&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(v, <span class="stringliteral">&quot;major&quot;</span>)) = 2.8;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ada27892570331f334c2622e5b6d371e1">value_atw</a>(v, L<span class="stringliteral">&quot;©&quot;</span>)) = 2015;  <span class="comment">/* wide string tags are OK */</span></div><div class="line"></div><div class="line"><span class="comment">/* create a base64-encoded image object */</span></div><div class="line"><span class="keyword">struct </span><a class="code" href="struct__base64.html">_base64</a> *img = <a class="code" href="xml-rpc_8h.html#a83e10b3bc3636f2aad1223d4ed8939d3">base64_of</a>(v);</div><div class="line">img-&gt;<a class="code" href="struct__base64.html#a61016779498f7591c59009407577438b">__ptr</a> = ptr_to_rawimage100bytes;  <span class="comment">/* block of 100 raw bytes */</span></div><div class="line">img-&gt;<a class="code" href="struct__base64.html#a6b3c5febc95166d9f931338afd312b1e">__size</a> = 100;</div></div><!-- fragment --><p>The functions above return a pointer to a specific type of value and this value can be assigned as shown above but also read. So we use these functions also to retrieve data, for example after receiving XML-RPC or JSON data.</p>
<p>We can combine this syntax in many possible ways to create arrays of arrays, arrays of structs, and so on. For example:</p>
<div class="fragment"><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;name&quot;</span>)) = <span class="stringliteral">&quot;bob&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;toys&quot;</span>), 0)) = <span class="stringliteral">&quot;ball&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;toys&quot;</span>), 1)) = <span class="stringliteral">&quot;furby&quot;</span>;</div></div><!-- fragment --><p>This creates a singleton array containing an object with two members: <code>name</code> set to <code>"bob"</code> and <code>toys</code> set to an array containing <code>"ball"</code> and <code>"furby"</code>. In JSON format this is represented as: </p><pre class="fragment">           [ { "name": "bob", "toys": ["ball", "furby"] } ]
           ^ ^ ^              ^
           | | |              |
  an array_/ | |              |
 of 1 struct_/ |              |
with 2 members_/______________/
</pre><p>Let's see what happens when we assign a variable the value of another.</p>
<p>The JSON C API uses the <em>reference model</em> for variables, meaning that values are shared when assigning a target variable the value of another variable. The variable values are shared until one or the other variables is assigned a different type of value. We illustrate the effect below:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *x = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx), *y = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x) = 1;</div><div class="line">*y = *x;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x) = 2;</div><div class="line">printf(<span class="stringliteral">&quot;x = %lld and y = %lld\n&quot;</span>, *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x), *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(y));</div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(x) = 3.1;</div><div class="line">printf(<span class="stringliteral">&quot;x = %g and y = %lld\n&quot;</span>, *<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(x), *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(y));</div></div><!-- fragment --><p>This prints <code>x = 2 and y = 2</code> and <code>x = 3.1 and y = 2</code>.</p>
<p>You can make a copy of an atomic value with one of the <code>Type_of()</code> functions. The following code illustrates how:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *x = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx), *y;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x) = 1;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(y) = *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x);</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x) = 2;</div><div class="line">printf(<span class="stringliteral">&quot;x = %lld and y = %lld\n&quot;</span>, *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(x), *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(y));</div></div><!-- fragment --><p>This prints <code>x = 2 and y = 1</code>.</p>
<p>You can also make deep copies of values by using the auto-generated <code>soap_dup_value</code> function in <code>soapC.c</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *a = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx), *b;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(a, 0)) = 1;</div><div class="line">b = soap_dup_value(ctx, NULL, a);</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(a, 0)) = 2;</div><div class="line">printf(<span class="stringliteral">&quot;a[0] = %lld and b[0] = %lld\n&quot;</span>, *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(a, 0)), *<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(b, 0)));</div></div><!-- fragment --><p>This prints <code>a[0] = 2 and b[0] = 1</code>.</p>
<p>To auto-generate <code>soap_dup_value</code>, use option <code>-Ec</code> with soapcpp2: </p><pre class="fragment">soapcpp2 -c -Ec -CSL xml-rpc.h
</pre><p>When receiving a value in XML-RPC or JSON, we generally want to check its type to obtain its value. To check the type of a value, we use <code>is_Type</code> functions:</p>
<div class="fragment"><div class="line"><a class="code" href="xml-rpc_8h.html#a9c006e0e0ea53fce5cbc6dd543b8127b">is_null</a>(v)     <span class="comment">/* true if value is not set (JSON null) */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a641eee093203fbd4a308e92b9eee1238">is_bool</a>(v)     <span class="comment">/* true if value is a Boolean &quot;true&quot; or &quot;false&quot; value */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a56a91404bf315af6dfe31786924dcd80">is_true</a>(v)     <span class="comment">/* true if value is Boolean &quot;true&quot; */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#aab4f39a727533199bc25a0dd57e539e7">is_false</a>(v)    <span class="comment">/* true if value is Boolean &quot;false&quot; */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a26f8409f8dd1b093bea7dbd036392be0">is_number</a>(v)   <span class="comment">/* true if value is a number (int or float) */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb">is_int</a>(v)      <span class="comment">/* true if value is a 32 or a 64 bit int */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028">is_double</a>(v)   <span class="comment">/* true if value is a 64 bit double floating point (not integer) */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(v)   <span class="comment">/* true if value is a string */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a06cf4ad42a3483b8a0da51f77aefa2bd">is_dateTime</a>(v) <span class="comment">/* true if ISO 8601, always false for received JSON */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>(v)    <span class="comment">/* true if array of values */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>(v)   <span class="comment">/* true if structure, a.k.a. a JSON object */</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a99a7e4bbd0637ef4e752896cf299cfb7">is_base64</a>(v)   <span class="comment">/* true if base64, always false for received JSON */</span></div></div><!-- fragment --><p>When working with JSON data, do not use <code><a class="el" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028" title="C function returns true if value is a 64 bit double floating point. ">is_double()</a></code> but <code><a class="el" href="xml-rpc_8h.html#a26f8409f8dd1b093bea7dbd036392be0" title="C function returns true if value is a number (int or float) ">is_number()</a></code>. JSON data does not differentiate between integers and floats. However, gSOAP makes sure that 64 bit integer values are accurately represented in JSON and decoded without loss from JSON. That is, when receiving an integer that you checked with <code><a class="el" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb" title="C function returns true if value is a 32 or a 64 bit int. ">is_int()</a></code> you can then safely retrieve the value with <code><a class="el" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612" title="C function returns pointer to int, coerces v to int if needed. ">int_of()</a></code>, for example <code>int64_t n = *int_of(v)</code>.</p>
<p>The following functions can be used with arrays and structs (JSON objects):</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> <a class="code" href="xml-rpc_8h.html#aa4d39cc0904084cdc556be1b43146542">set_struct</a>(v)                         <span class="comment">/* reset/create an empty struct */</span></div><div class="line">void <a class="code" href="xml-rpc_8h.html#a4923910fea4fc3bcb85ec655f1071a66">set_size</a>(v, <span class="keywordtype">int</span>)                      <span class="comment">/* reset/change array size or pre-allocate space */</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v)                            <span class="comment">/* returns array or struct size or 0 */</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="xml-rpc_8h.html#adc4960a06b10ec7aef4892260c31f2fd">is_empty</a>(v)                            <span class="comment">/* returns 1 if array or struct is empty or 0 */</span></div><div class="line">struct <a class="code" href="structvalue.html">value</a> *<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, <span class="keywordtype">int</span>)            <span class="comment">/* returns nth value in array or struct */</span></div><div class="line">struct <a class="code" href="structvalue.html">value</a> *<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(v, const <span class="keywordtype">char</span>*)     <span class="comment">/* returns value at field in struct */</span></div><div class="line">struct <a class="code" href="structvalue.html">value</a> *<a class="code" href="xml-rpc_8h.html#ada27892570331f334c2622e5b6d371e1">value_atw</a>(v, const <span class="keywordtype">wchar_t</span>*) <span class="comment">/* returns value at field in struct */</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="xml-rpc_8h.html#af2855dca8d5186e4eef15f1e30a29916">nth_at</a>(v, const <span class="keywordtype">char</span>*)                 <span class="comment">/* returns nth index of field in struct or -1 */</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="xml-rpc_8h.html#a75c655d6c8f4c1d724574c9d2ef9c656">nth_atw</a>(v, const <span class="keywordtype">wchar_t</span>*)             <span class="comment">/* returns nth index of field in struct or -1 */</span></div><div class="line"><span class="keywordtype">int</span> <a class="code" href="xml-rpc_8h.html#a434cc3569bccca76d161c4b3b97a4d9c">nth_nth</a>(v, <span class="keywordtype">int</span>)                        <span class="comment">/* returns nth index if nth index exists in array or -1 */</span></div></div><!-- fragment --><p>When accessing structs (JSON objects) with <code>value_at</code>, make sure to use existing member field names only. A new member fieldname-value pair is dynamically added to the structure to accomodate the new entry for the field.</p>
<p>Also arrays are extended with <code>nth_value</code> to accommodate the indexed array element.</p>
<p>A negative array index indexes elements from the end of the array, with index -1 accessing the array's last value.</p>
<p>Use <code>set_size</code> to change array size or set arrays to zero length. Use negative size with <code>set_size</code> to remove elements from the end.</p>
<p>For example, let's take the value <code>v</code> that was assigned the array shown above. We have the following properties of this value:</p>
<div class="fragment"><div class="line"><a class="code" href="xml-rpc_8h.html#a9c006e0e0ea53fce5cbc6dd543b8127b">is_null</a>(v) == <span class="keyword">false</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>(v) == <span class="keyword">true</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v) == 1</div><div class="line"><a class="code" href="xml-rpc_8h.html#adc4960a06b10ec7aef4892260c31f2fd">is_empty</a>(v) == 0</div><div class="line"><a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0)) == <span class="keyword">true</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#af2855dca8d5186e4eef15f1e30a29916">nth_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;name&quot;</span>) == 0</div><div class="line"><a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;name&quot;</span>)) == <span class="keyword">true</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;toys&quot;</span>), 0)) == <span class="keyword">true</span></div><div class="line"><a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, 0), <span class="stringliteral">&quot;toys&quot;</span>), 1)) == <span class="keyword">true</span></div></div><!-- fragment --><p>Considering that the code verbosity quickly increases when accessing deeper levels of your structures, you are probably inclined to define your own macros to create and access deep data more conveniently, such as:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#define string_at(v, s) string_of(value_at((v), (s)))</span></div><div class="line"><span class="preprocessor">#define nth_string(v, n) string_of(nth_value((v), (n)))</span></div><div class="line"><span class="preprocessor">#define nth_string_at(v, s, n) string_of(nth_value(value_at((v), (s)), (n)))</span></div><div class="line"><span class="preprocessor">#define string_at_nth(v, n, s) string_of(value_at(nth_value((v), (n)), (s)))</span></div><div class="line"><span class="preprocessor">#define nth_string_at_nth(v, n, s, m) string_of(nth_value(value_at(nth_value((v), (n)), (s)), (m)))</span></div><div class="line">... etc ...</div><div class="line">*string_at_nth(v, 0, <span class="stringliteral">&quot;name&quot;</span>) = <span class="stringliteral">&quot;bob&quot;</span>;</div><div class="line">*nth_string_at_nth(v, 0, <span class="stringliteral">&quot;toys&quot;</span>, 0) = <span class="stringliteral">&quot;ball&quot;</span>;</div><div class="line">*nth_string_at_nth(v, 0, <span class="stringliteral">&quot;toys&quot;</span>, 1) = <span class="stringliteral">&quot;furby&quot;</span>;</div></div><!-- fragment --><p>To iterate over array and struct values, we use a loop over <code>nth_value</code> and <code>nth_member</code> as follows:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>(v))</div><div class="line">{</div><div class="line">  <span class="keywordtype">int</span> i;</div><div class="line">  <span class="keywordflow">for</span> (i = 0; i &lt; <a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v); i++)</div><div class="line">  {</div><div class="line">    <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *array_value = <a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, i);</div><div class="line">    ... <span class="comment">/* use and/or set array_value */</span></div><div class="line">  }</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>(v))</div><div class="line">{</div><div class="line">  <span class="keywordtype">int</span> i;</div><div class="line">  <span class="keywordflow">for</span> (i = 0; i &lt; <a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v); i++)</div><div class="line">  {</div><div class="line">    <span class="keyword">struct </span><a class="code" href="structmember.html">member</a> *<a class="code" href="structmember.html">member</a> = <a class="code" href="xml-rpc_8h.html#a9d1e5a8876f8fc0f27449180847de769">nth_member</a>(v, i);</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span> *member_name = member-&gt;<a class="code" href="structmember.html#ac0e09df49f775db12416340f2baf06e9">name</a>;</div><div class="line">    <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *member_value = &amp;member-&gt;<a class="code" href="structmember.html#a90c76b22cb6d3433203e6f745e862215">value</a>;</div><div class="line">    ... <span class="comment">/* use member_name and member_value */</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>To access base64 binary raw data of a value <code>v</code>, we use the following code:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span><a class="code" href="struct__base64.html">_base64</a> *base64 = <a class="code" href="xml-rpc_8h.html#a83e10b3bc3636f2aad1223d4ed8939d3">base64_of</a>(v);</div><div class="line"><span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *raw = base64-&gt;<a class="code" href="struct__base64.html#a61016779498f7591c59009407577438b">__ptr</a>;  <span class="comment">/* point to raw binary data */</span></div><div class="line"><span class="keywordtype">int</span> size = base64-&gt;<a class="code" href="struct__base64.html#a6b3c5febc95166d9f931338afd312b1e">__size</a>;           <span class="comment">/* that is of this size */</span></div></div><!-- fragment --><p>XML-RPC parameter lists are similar to arrays and its values are indexed. We can also loop over response parameters after an XML-RPC REST call:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span><a class="code" href="structparams.html">params</a> *request = <a class="code" href="xml-rpc_8h.html#addbe5187fa70ee2a97526986e14a7c61">new_params</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structmethod_response.html">methodResponse</a> response;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 0)) = <span class="stringliteral">&quot;hello&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 1)) = <span class="stringliteral">&quot;world&quot;</span>;</div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#ac3e3a566230b35d7fe51d7b72a14b5a6">call_method</a>(ctx, <span class="stringliteral">&quot;endpoint URL&quot;</span>, <span class="stringliteral">&quot;methodName&quot;</span>, request, &amp;response) == SOAP_OK)</div><div class="line">{</div><div class="line">  <span class="keywordtype">int</span> i;</div><div class="line">  <span class="keywordflow">for</span> (i = 0; i &lt; response.<a class="code" href="structparams.html#a20bbc13222589486dd7799ae4a20b260">params</a>-&gt;__size; i++)</div><div class="line">  {</div><div class="line">    <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *param_value = <a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(response.<a class="code" href="structparams.html#a20bbc13222589486dd7799ae4a20b260">params</a>, i);</div><div class="line">    ... <span class="comment">/* use param_value */</span></div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>We should note that JSON REST does not require parameter types, for example:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *response = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(request, 0)) = <span class="stringliteral">&quot;hello&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(request, 1)) = <span class="stringliteral">&quot;world&quot;</span>;</div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(cts, <span class="stringliteral">&quot;endpoint URL&quot;</span>, request, response) == SOAP_OK)</div><div class="line">{</div><div class="line">  ... <span class="comment">/* use response value */</span></div><div class="line">}</div></div><!-- fragment --><p>All dynamically allocated memory that is internally used to store data is deallocated with:</p>
<div class="fragment"><div class="line">soap_end(ctx);      <span class="comment">/* delete all values */</span></div><div class="line">soap_free(ctx);     <span class="comment">/* delete context allocated with soap_new() */</span></div></div><!-- fragment --><p>Additional examples are located in <code>gsoap/samples/xml-rpc-json</code>:</p>
<ul>
<li><code>json-currentTime.c</code> JSON REST C client</li>
<li><code>json-currentTimeServer.c</code> JSON REST C server (CGI and multi-threaded stand-alone)</li>
<li><code>json-GitHub.c</code>: JSON C client for GitHub API v3</li>
<li><code>xml-rpc-currentTime.c</code> XML-RPC C client</li>
<li><code>xml-rpc-weblogs.c</code> XML-RPC C client</li>
</ul>
<h2><a class="anchor" id="c-cl"></a>
C XML-RPC client example                                                 </h2>
<p>An XML-RPC method call in C with the new XML-RPC C API:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;soapH.h&quot;</span>  <span class="comment">/* generated by the command: soapcpp2 -CSL xml-rpc.h */</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING); <span class="comment">/* UTF-8 in char* strings */</span></div><div class="line"><span class="keyword">struct </span><a class="code" href="structparams.html">params</a> *request = <a class="code" href="xml-rpc_8h.html#addbe5187fa70ee2a97526986e14a7c61">new_params</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structmethod_response.html">methodResponse</a> response;</div><div class="line">ctx-&gt;send_timeout = 10; <span class="comment">/* 10 sec, stop if server is not accepting msg */</span></div><div class="line">ctx-&gt;recv_timeout = 10; <span class="comment">/* 10 sec, stop if server does not respond in time */</span></div><div class="line"><span class="comment">/* first parameter is an integer */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 0)) = 123;</div><div class="line"><span class="comment">/* second parameter is a string */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 1)) = <span class="stringliteral">&quot;abc&quot;</span>;</div><div class="line"><span class="comment">/* third parameter is a struct {&quot;name&quot;: &quot;joe&quot;, &quot;age&quot;: 23} */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 2), <span class="stringliteral">&quot;name&quot;</span>)) = <span class="stringliteral">&quot;joe&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 2), <span class="stringliteral">&quot;age&quot;</span>)) = 23;</div><div class="line"><span class="comment">/* fourth parameter is an array [456.789, &quot;widget&quot;, true] */</span></div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 3), 0)) = 456.789</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 3), 1)) = <span class="stringliteral">&quot;widget&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#a1f8f465811b8a8a5f2c186c52273399a">bool_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(request, 3), 2)) = 1;</div><div class="line"><span class="comment">/* connect, send request, and receive response */</span></div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#ac3e3a566230b35d7fe51d7b72a14b5a6">call_method</a>(ctx, <span class="stringliteral">&quot;endpoint UTL&quot;</span>, <span class="stringliteral">&quot;methodName&quot;</span> request, &amp;response))</div><div class="line">{</div><div class="line">  soap_print_fault(ctx, stderr);</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (response.fault)</div><div class="line">{</div><div class="line">  <span class="comment">/* write fault to stdout */</span></div><div class="line">  soap_write_fault(ctx, response.fault);</div><div class="line">}</div><div class="line"><span class="keywordflow">else</span></div><div class="line">{</div><div class="line">  <span class="comment">/* print response parameters */</span></div><div class="line">  <span class="keywordtype">int</span> i;</div><div class="line">  <span class="keywordflow">for</span> (i = 0; i &lt; response.params-&gt;__size; i++)</div><div class="line">  {</div><div class="line">    printf(<span class="stringliteral">&quot;Return parameter %d = &quot;</span>, i+1);</div><div class="line">    display(<a class="code" href="xml-rpc_8h.html#afa8532c872d5430daa49add5c5f1f7d6">nth_param</a>(response.params, i)); <span class="comment">/* see below */</span></div><div class="line">    printf(<span class="stringliteral">&quot;\n&quot;</span>);</div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p>The following example shows how to traverse the node graph to display a value:</p>
<div class="fragment"><div class="line"><span class="keywordtype">void</span> display(<span class="keyword">struct</span> <a class="code" href="structvalue.html">value</a> *v)</div><div class="line">{</div><div class="line">  <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a641eee093203fbd4a308e92b9eee1238">is_bool</a>(v))</div><div class="line">    printf(<a class="code" href="xml-rpc_8h.html#a56a91404bf315af6dfe31786924dcd80">is_true</a>(v) ? <span class="stringliteral">&quot;true&quot;</span> : <span class="stringliteral">&quot;false&quot;</span>);</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#aa556973b4edbc381e75f6172655a7bdb">is_int</a>(v))</div><div class="line">    printf(<span class="stringliteral">&quot;%lld&quot;</span>, <a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(v));</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#aa68cb9d2950d826fcc0ce19cfe40c028">is_double</a>(v))</div><div class="line">    printf(<span class="stringliteral">&quot;%lG&quot;</span>, <a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(v));</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(v))</div><div class="line">    printf(<span class="stringliteral">&quot;\&quot;%s\&quot;&quot;</span>, <a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(v));</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a5c966917360d8b05046f2625cc146176">is_array</a>(v))</div><div class="line">  {</div><div class="line">    <span class="keywordtype">int</span> i;</div><div class="line">    printf(<span class="stringliteral">&quot;[&quot;</span>);</div><div class="line">    <span class="keywordflow">for</span> (i = 0; i &lt; <a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v); i++)</div><div class="line">    {</div><div class="line">      <span class="keywordflow">if</span> (i) printf(<span class="stringliteral">&quot;,&quot;</span>);</div><div class="line">      display(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(v, i));</div><div class="line">    }</div><div class="line">    printf(<span class="stringliteral">&quot;]&quot;</span>);</div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#aa520242cc045c4390b6e79d6e02b372d">is_struct</a>(v))</div><div class="line">  {</div><div class="line">    <span class="keywordtype">int</span> i;</div><div class="line">    printf(<span class="stringliteral">&quot;{&quot;</span>);</div><div class="line">    <span class="keywordflow">for</span> (i = 0; i &lt; <a class="code" href="xml-rpc_8h.html#a12cc6102a5617ffba09d3a186289214f">has_size</a>(v); i++)</div><div class="line">    {</div><div class="line">      <span class="keywordflow">if</span> (i) printf(<span class="stringliteral">&quot;,&quot;</span>);</div><div class="line">      printf(<span class="stringliteral">&quot;\&quot;%s\&quot;: &quot;</span>, <a class="code" href="xml-rpc_8h.html#a9d1e5a8876f8fc0f27449180847de769">nth_member</a>(v, i)-&gt;name);</div><div class="line">      display(&amp;<a class="code" href="xml-rpc_8h.html#a9d1e5a8876f8fc0f27449180847de769">nth_member</a>(v, i)-&gt;<a class="code" href="structvalue.html">value</a>);</div><div class="line">    }</div><div class="line">    printf(<span class="stringliteral">&quot;}&quot;</span>);</div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a06cf4ad42a3483b8a0da51f77aefa2bd">is_dateTime</a>(v))</div><div class="line">    printf(<span class="stringliteral">&quot;\&quot;%s\&quot;&quot;</span>, <a class="code" href="xml-rpc_8h.html#ad4147857ac2f220b7eae794d66f18810">dateTime_of</a>(v));</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a99a7e4bbd0637ef4e752896cf299cfb7">is_base64</a>(v))</div><div class="line">    printf(<span class="stringliteral">&quot;(%d bytes of raw data at %p)&quot;</span>, <a class="code" href="xml-rpc_8h.html#a83e10b3bc3636f2aad1223d4ed8939d3">base64_of</a>(v)-&gt;__size, <a class="code" href="xml-rpc_8h.html#a83e10b3bc3636f2aad1223d4ed8939d3">base64_of</a>(v)-&gt;__ptr);</div><div class="line">}</div></div><!-- fragment --><p>Compile and link your code together with <code>soapC.c</code> (generated), <code>xml-rpc.c</code>, and <code>stdsoap2.c</code>.</p>
<h2><a class="anchor" id="c-js"></a>
C JSON serialization                                                     </h2>
<p>To write values in JSON format or parse JSON data, we use the <code><a class="el" href="json_8h.html">json.h</a></code> and <code>json.c</code> JSON C API. It is also possible to send and receive JSON data over HTTP (JSON REST).</p>
<p>Reading and writing XML from/to files, streams and string buffers is done via the managing context by setting one of the following context members that control IO sources and sinks:</p>
<div class="fragment"><div class="line">ctx-&gt;recvfd = fd; <span class="comment">// an int file descriptor to read from (0 by default)</span></div><div class="line">ctx-&gt;sendfd = fd; <span class="comment">// an int file descriptor to write to (1 by default)</span></div><div class="line">ctx-&gt;is = cs;     <span class="comment">// C only: a const char* string to read from (soap-&gt;is will advance)</span></div><div class="line">ctx-&gt;os = &amp;cs;    <span class="comment">// C only: pointer to a const char*, will be set to point to the string output</span></div></div><!-- fragment --><p>For example, to read and write JSON data from/to a file descriptor:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span> <span class="comment">/* also compile and link json.c */</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">/* no XML namespaces */</span></div><div class="line"></div><div class="line"><span class="comment">/* SOAP_C_UTFSTRING: UTF-8 content in char*, SOAP_XML_INDENT: indent JSON */</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"></div><div class="line">ctx-&gt;recvfd = ...;         <span class="comment">/* set int file descriptor for reading */</span></div><div class="line"><a class="code" href="json_8h.html#a927016fe60cb59422e4769dd7803462c">json_read</a>(ctx, v);         <span class="comment">/* read JSON into value v */</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...        <span class="comment">/* handle IO error (error message is in &#39;v&#39; */</span></div><div class="line"></div><div class="line">ctx-&gt;sendfd = ...;         <span class="comment">/* set int file descriptor for writing */</span></div><div class="line"><a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, v);        <span class="comment">/* write value v in JSON format (indented) */</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...        <span class="comment">/* handle IO error (error message is in &#39;v&#39; */</span></div></div><!-- fragment --><p>To force reading and writing JSON in ISO 8859-1 format, use the <code>SOAP_ENC_LATIN</code> flag to initialize the context (not recommended).</p>
<p>Optionally use <code>SOAP_XML_INDENT</code> to indent XML and JSON output.</p>
<p>To parse JSON values from a file or from any other non-HTTP source, it is recommended to set the <code>SOAP_ENC_PLAIN</code> context flag to prevent the parser from attempting to read a MIME or HTTP headers (HTTP headers are required with JSON-RPC):</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT | SOAP_ENC_PLAIN);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><a class="code" href="json_8h.html#a927016fe60cb59422e4769dd7803462c">json_read</a>(ctx, v);         <span class="comment">/* read JSON without parsing MIME/HTTP header */</span></div></div><!-- fragment --><p>You can also read and write JSON data from/to NUL-terminated strings:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}};</div><div class="line"></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT | SOAP_ENC_PLAIN);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"></div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *cs = <span class="stringliteral">&quot;[1, 2, 3]&quot;</span>;</div><div class="line"></div><div class="line">ctx-&gt;is = cs;</div><div class="line"><a class="code" href="json_8h.html#a927016fe60cb59422e4769dd7803462c">json_read</a>(ctx, v);         <span class="comment">/* read JSON array from cs into value v */</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...        <span class="comment">/* handle IO error (error message is in &#39;v&#39; */</span></div><div class="line"></div><div class="line">cs = NULL;</div><div class="line">ctx-&gt;os = &amp;cs;</div><div class="line"><a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, v);        <span class="comment">/* write value v in JSON format (indented) and set cs */</span></div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...        <span class="comment">/* handle IO error (error message is in &#39;v&#39; */</span></div><div class="line">printf(<span class="stringliteral">&quot;JSON data:\n%s\n&quot;</span>, cs);</div></div><!-- fragment --><p>Compile and link your code together with <code>soapC.c</code> (generated), <code>xml-rpc.c</code>, <code>json.c</code>, and <code>stdsoap2.c</code>.</p>
<p>You can also convert XML-RPC data to/from JSON and populate XML-RPC from JSON data. The XML-RPC parsing and sending functions are <code>soap_read_value</code> and <code>soap_write_value</code>, respectively.</p>
<p>The JSON protocol has fewer data types than XML-RPC, so type information can be lost when serializing to JSON:</p>
<ul>
<li>XML-RPC uses a base64 type to exchange raw binary data. The base64 data is converted to a string with base64 content by the JSON serializer. See also <a class="el" href="index.html#base64">JSON and base64 </a>.</li>
<li>XML-RPC has a dateTime type, JSON does not. The JSON serializer converts the dateTime type to a dateTime-formatted string. See also <a class="el" href="index.html#dateTime">JSON and ISO 8601 dateTime </a>.</li>
</ul>
<p>Strings are stored and exchanged in UTF-8 format in 8-bit strings (i.e. <code>char*</code> strings) with the <code>SOAP_C_UTFSTRING</code> flag. Wide strings (i.e. <code>wchar_t*</code> strings) are converted to UTF-8.</p>
<p>To read JSON from a string and write JSON to a string, we suggest to use gSOAP 2.8.28 or later. With these newer versions you can set the contex input string <code>ctx-&gt;is</code> to the string to parse (reset to NULL afterwards) as follows:</p>
<div class="fragment"><div class="line"><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">ctx-&gt;is = <span class="stringliteral">&quot;[ [1, \&quot;2\&quot;, 3.14, true], {\&quot;name\&quot;: \&quot;john\&quot;, \&quot;age\&quot;: 24} ]&quot;</span>: </div><div class="line"><a class="code" href="json_8h.html#a927016fe60cb59422e4769dd7803462c">json_read</a>(ctx, v);</div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ... <span class="comment">/* handle IO error (error message is in &#39;v&#39; */</span></div><div class="line">ctx-&gt;is = NULL;     <span class="comment">/* stop reading from string */</span></div></div><!-- fragment --><p>You can set the context output string pointer <code>ctx-&gt;os</code> to point to the <code>const char*</code> string that you want to be set. This string will point to the JSON data created by the engine and managed by the context as follows:</p>
<div class="fragment"><div class="line"><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *json_out = NULL;</div><div class="line">... <span class="comment">/* populate value v */</span></div><div class="line">ctx-&gt;os = &amp;json_out; <span class="comment">/* the string to point to JSON data */</span></div><div class="line"><a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, v);</div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...</div><div class="line">ctx-&gt;os = NULL;      <span class="comment">/* stop writing to strings */</span></div><div class="line"><span class="keywordflow">if</span> (json_out)</div><div class="line">{</div><div class="line">  ... <span class="comment">/* use json_out string, do not free() (managed by the context) */</span></div><div class="line">}</div><div class="line">...</div><div class="line">soap_end(ctx);  <span class="comment">/* deletes json_out string */</span></div></div><!-- fragment --><p>For older versions prior to 2.8.28, the gSOAP engine's IO <code>frecv</code> callback function can be used as follows to parse JSON from a string buffer:</p>
<div class="fragment"><div class="line"><span class="keywordtype">size_t</span> buf_recv(<span class="keyword">struct</span> <a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a> *ctx, <span class="keywordtype">char</span> *buf, <span class="keywordtype">size_t</span> len)</div><div class="line">{</div><div class="line">  <span class="keyword">const</span> <span class="keywordtype">char</span> *in = (<span class="keywordtype">char</span>*)ctx-&gt;user;  <span class="comment">/* get handle to input string */</span></div><div class="line">  <span class="keywordtype">size_t</span> n = strlen(in);</div><div class="line">  <span class="keywordflow">if</span> (n &gt; len) <span class="comment">/* if in[] is larger than buf[] len */</span></div><div class="line">    n = len;   <span class="comment">/* then cap length at len */</span></div><div class="line">  memcpy(buf, in, n);</div><div class="line">  in += n;</div><div class="line">  ctx-&gt;user = (<span class="keywordtype">void</span>*)in;  <span class="comment">/* update the handle */</span></div><div class="line">  <span class="keywordflow">return</span> n;</div><div class="line">}</div><div class="line">...</div><div class="line">value *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *json_in = <span class="stringliteral">&quot;[ [1, \&quot;2\&quot;, 3.14, true], {\&quot;name\&quot;: \&quot;john\&quot;, \&quot;age\&quot;: 24} ]&quot;</span>: </div><div class="line">ctx-&gt;frecv = buf_recv;</div><div class="line">ctx-&gt;user = (<span class="keywordtype">void</span>*)json_in;  <span class="comment">/* a user handle that is passed to buf_recv */</span></div><div class="line"><a class="code" href="json_8h.html#a927016fe60cb59422e4769dd7803462c">json_read</a>(ctx, v);</div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...</div></div><!-- fragment --><p>For older versions prior to 2.8.28, the gSOAP engine IO <code>fsend</code> callback function can be used to write JSON to strings as follows:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#define BUFFER_INCREMENT (1024)</span></div><div class="line"><span class="keywordtype">int</span> buf_send(<span class="keyword">struct</span> <a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a> *ctx, <span class="keyword">const</span> <span class="keywordtype">char</span> *buf, <span class="keywordtype">size_t</span> len)</div><div class="line">{</div><div class="line">  <span class="keywordtype">char</span> *out = (<span class="keywordtype">char</span>*)ctx-&gt;user;  <span class="comment">/* get handle to current buffer, if any */</span></div><div class="line">  <span class="keywordtype">size_t</span> n = out ? strlen(out) : 0;</div><div class="line">  <span class="keywordtype">size_t</span> k = (n + len + 1)/BUFFER_INCREMENT;</div><div class="line">  <span class="keywordflow">if</span> (!out)  <span class="comment">/* first time around? */</span></div><div class="line">  {</div><div class="line">    out = malloc((k + 1) * BUFFER_INCREMENT);</div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span> <span class="keywordflow">if</span> (n/BUFFER_INCREMENT &lt; k)  <span class="comment">/* need to increase buffer? */</span></div><div class="line">  {</div><div class="line">    <span class="keywordtype">char</span> *more = malloc((k + 1) * BUFFER_INCREMENT);</div><div class="line">    memcpy(more, out, n);</div><div class="line">    free(out);</div><div class="line">    out = more;</div><div class="line">  }</div><div class="line">  memcpy(out + n, buf, len);</div><div class="line">  out[n + len] = <span class="charliteral">&#39;\0&#39;</span>;</div><div class="line">  ctx-&gt;user = (<span class="keywordtype">void</span>*)out;</div><div class="line">  <span class="keywordflow">return</span> SOAP_OK;</div><div class="line">}</div><div class="line">...</div><div class="line">value *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *json_out;</div><div class="line">... <span class="comment">/* populate value v */</span></div><div class="line">ctx-&gt;fsend = buf_send;</div><div class="line">ctx-&gt;user = NULL;</div><div class="line"><a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, v);</div><div class="line"><span class="keywordflow">if</span> (ctx-&gt;error) ...</div><div class="line">json_out = (<span class="keywordtype">char</span>*)ctx-&gt;user;</div><div class="line">if (json_out)</div><div class="line">{</div><div class="line">  ... <span class="comment">/* use json_out string */</span></div><div class="line">  free(json_out);</div><div class="line">  ctx-&gt;user = NULL;</div><div class="line">}</div></div><!-- fragment --><h2><a class="anchor" id="c-jr"></a>
C JSON REST clients and servers                                          </h2>
<p>To use JSON REST on the client side, we use <code>json_call</code>:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span>             <span class="comment">/* also compile and link json.c */</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">/* no XML namespaces */</span></div><div class="line"></div><div class="line"><span class="comment">/* SOAP_C_UTFSTRING: UTF-8 content in char*, SOAP_XML_INDENT: indent JSON */</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> response;</div><div class="line">... <span class="comment">/* here we populate the request data to send */</span></div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(ctx, <span class="stringliteral">&quot;endpoint URL&quot;</span>, request, &amp;response))</div><div class="line">  ... <span class="comment">/* error */</span></div><div class="line">... <span class="comment">/* use the response data */</span></div><div class="line">soap_end(ctx); <span class="comment">/* delete all values */</span></div><div class="line">... <span class="comment">/* here we can make other calls etc. */</span></div><div class="line">soap_free(ctx); <span class="comment">/* delete the context */</span></div></div><!-- fragment --><p>The <code>json_call</code> function takes a context, an endpoint URL (with query string parameters as needed), and optional <code>in</code> and <code>out</code> values to send and receive, respectively. The function returns <code>SOAP_OK</code> (zero) for success or <code>EOF</code>, <code>SOAP_SYNTAX_ERROR</code>, or an HTTP error code.</p>
<p>To use the JSON REST POST method, pass both <code>in</code> and <code>out</code> values to <code>json_call</code>. For the GET method, pass a NULL to <code>in</code>. For the PUT method, pass a NULL to <code>out</code>. For the DELETE method, pass both NULL to <code>in</code> and <code>out</code>.</p>
<p>Besides <code>json_call</code>, there are other JSON API functions:</p>
<ul>
<li><code>int json_call(struct soap *ctx, const char *URL, struct value *in, struct value *out)</code> makes a POST, GET, PUT, DELETE call, returns <code>SOAP_OK</code> or error code. POST method: pass both <code>in</code> and <code>out</code>. GET method: pass a NULL to <code>in</code>. PUT method: pass a NULL to <code>out</code>. DELETE method: pass both NULL to <code>in</code> and <code>out</code>. <code>SOAP_OK</code> is returned for POST and GET methods upon success. An HTTP status code of 200 (OK) or 202 (Accepted) is returned for PUT and DELETE methods upon success.</li>
<li><code>int <a class="el" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50" title="Write JSON value to the context&#39;s output (socket, stream, FILE, or string) ">json_write(struct soap *ctx, const struct value *v)</a></code> Writes JSON value to current file or socket. Returns <code>SOAP_OK</code> or error. Set current file/socket file descriptor with <code>ctx-&gt;sendfd = fd</code>. Or save JSON to a string by setting <code>ctx-&gt;os = &amp;cs</code> with <code>const char *cs</code> a string pointer that will be set to a NUL-terminated string when the write completed.</li>
<li><code>int <a class="el" href="json_8h.html#a927016fe60cb59422e4769dd7803462c" title="Read JSON value from context&#39;s input (socket, stream, FILE, or string) ">json_read(struct soap *ctx, struct value *v)</a></code> Reads JSON value from current file or socket. Returns <code>SOAP_OK</code> or error. Set current file/socket file descriptor with <code>ctx-&gt;recvfd = fd</code>. Or read from string by setting <code>ctx-&gt;is = cs</code> to a <code>const char *cs</code> NUL-terminated string.</li>
</ul>
<p>The are two other lower-level functions <code>json_send</code> and <code>json_recv</code> that are similar to <code>json_write</code> and <code>json_read</code> but do not initialize the sending and receiving operations and do not flush after the sending and receiving operations.</p>
<p>Compile and link your code together with <code>soapC.c</code> (generated), <code>xml-rpc.c</code>, <code>json.c</code>, and <code>stdsoap2.c</code>.</p>
<p>To implement a JSON REST server for CGI (e.g. install in cgi-bin):</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span>            <span class="comment">// also compile and link json.c</span></div><div class="line"><span class="keyword">struct </span>Namespace namespaces[] = {{NULL,NULL,NULL,NULL}}; <span class="comment">// no XML namespaces</span></div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main()</div><div class="line">{</div><div class="line">  <span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT | SOAP_ENC_PLAIN);</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *response = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keywordflow">if</span> (soap_begin_recv(ctx)</div><div class="line">   || <a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request)</div><div class="line">   || soap_end_recv(ctx))</div><div class="line">  {</div><div class="line">    <a class="code" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01">json_send_fault</a>(ctx); <span class="comment">// return a JSON-formatted fault</span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span></div><div class="line">  {</div><div class="line">    ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">    ... <span class="comment">// set the &#39;response&#39; value</span></div><div class="line">    <span class="comment">// set http content type</span></div><div class="line">    ctx-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line">    <span class="comment">// send http header 200 OK and JSON response</span></div><div class="line">    <span class="keywordflow">if</span> (soap_response(ctx, SOAP_FILE)</div><div class="line">     || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(ctx, response)</div><div class="line">     || soap_end_send(ctx))</div><div class="line">      soap_closesock(ctx);</div><div class="line">  }</div><div class="line">  <span class="comment">// dealloc all</span></div><div class="line">  soap_end(ctx);</div><div class="line">  soap_free(ctx);</div><div class="line">}</div></div><!-- fragment --><p>The above server works with CGI, which is rather slow and stateless. A stand-alone JSON REST server is recommended. You can also use the Apache and IIS plugins for gSOAP to deploy JSON REST services. See the <a href="https://www.genivia.com/docs.html">documentation</a>.</p>
<p>Note that we use <code><a class="el" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01" title="Respond with a JSON error when an internal fault occurred (i.e. soap-&gt;error is nonzero), as per Google JSON Style Guide. ">json_send_fault()</a></code> instead of <code>soap_send_fault()</code> when an internal error occurred, since we want the error to be reported in JSON format as per Google JSON Style Guide. For application-specific errors, we use <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> as follows:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (some application error occurred)</div><div class="line">  <a class="code" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0">json_send_error</a>(ctx, 400, <span class="stringliteral">&quot;Error message&quot;</span>, <span class="stringliteral">&quot;Error details&quot;</span>);</div><div class="line"><span class="keywordflow">else</span></div><div class="line">  ... <span class="comment">// send the response</span></div></div><!-- fragment --><p>You can specify an HTTP error code such as 400 in this case, which means that a HTTP 400 Bad Request is returned to the client.</p>
<p>The <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> function is a convenient shortcut to return an error message with an HTTP error code. To return a JSON response with a HTTP error code use the following:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> status = 400; <span class="comment">// HTTP 400 Bad Request</span></div><div class="line"><a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line"><span class="keywordflow">if</span> (soap_response(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>, SOAP_FILE + status)</div><div class="line"> || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>, v)</div><div class="line"> || soap_end_send(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>))</div><div class="line">  soap_closesock(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>);</div></div><!-- fragment --><p>The code for a stand-alone server is the same, except that we call <code>soap_bind()</code> and <code>soap_accept()</code> to serve requests on a port. Here is a simple iterative server serving requests on port 8080:</p>
<div class="fragment"><div class="line"><span class="comment">// create an allocation context</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_IO_KEEPALIVE | SOAP_C_UTFSTRING);</div><div class="line"><span class="comment">// bind to port 8080</span></div><div class="line"><span class="keywordflow">if</span> (!soap_valid_socket(soap_bind(ctx, NULL, 8080, 100)))</div><div class="line">  ... <span class="comment">// error, stop</span></div><div class="line"><span class="comment">// accept messages in server loop</span></div><div class="line"><span class="keywordflow">for</span> (;;)</div><div class="line">{</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *response = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keywordflow">if</span> (!soap_valid_socket(soap_accept(ctx)))</div><div class="line">    ... <span class="comment">// error, stop</span></div><div class="line">  <span class="keywordflow">if</span> (soap_begin_recv(ctx)</div><div class="line">   || <a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request)</div><div class="line">   || soap_end_recv(ctx))</div><div class="line">  {</div><div class="line">    <a class="code" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01">json_send_fault</a>(ctx); <span class="comment">// return a JSON-formatted fault</span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">else</span></div><div class="line">  {</div><div class="line">    ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">    ... <span class="comment">// set the &#39;response&#39; value</span></div><div class="line">    <span class="comment">// set http content type</span></div><div class="line">    ctx-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line">    <span class="comment">// send http header 200 OK and JSON response</span></div><div class="line">    <span class="keywordflow">if</span> (soap_response(ctx, SOAP_FILE)</div><div class="line">     || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(ctx, response)</div><div class="line">     || soap_end_send(ctx))</div><div class="line">      soap_closesock(ctx);</div><div class="line">  }</div><div class="line">  <span class="comment">// dealloc all</span></div><div class="line">  soap_end(ctx);</div><div class="line">}</div><div class="line">soap_free(ctx);</div></div><!-- fragment --><p>Note that <code>SOAP_ENC_PLAIN</code> should be used with CGI, since we are reading from a non-HTTP source with CGI. Do not use this flag with gSOAP stand-alone servers. Iterative stand-alone services are not performant and may block requests. We recommend stand-alone multi-threaded services.</p>
<p>Compile and link your code together with <code>soapC.c</code> (generated with <code>soapcpp2 -c -CSL <a class="el" href="xml-rpc_8h.html">xml-rpc.h</a></code>), <code>xml-rpc.c</code>, <code>json.c</code>, and <code>stdsoap2.c</code>.</p>
<p>For client and server examples, please see the gSOAP package content in <code>gsoap/samples/xml-rpc-json</code>:</p>
<ul>
<li><code>json-currentTime.c</code> JSON REST C client</li>
<li><code>json-currentTimeServer.c</code> JSON REST C server (CGI and multi-threaded stand-alone)</li>
</ul>
<p>The presentation in this section concerned stand-alone JSON REST services. To combine SOAP/XML with JSON REST services, see <a class="el" href="index.html#soap">Serving JSON and SOAP requests on the same server port </a> for details.</p>
<h2><a class="anchor" id="c-rpc"></a>
C JSON-RPC clients and servers                                          </h2>
<p>The <a href="http://json-rpc.org/wiki/specification">JSON-RPC 1.0 specification</a> (the "original version") adds <code>method</code>, <code>parameter</code> and <code>id</code> fields to the request message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;method&quot;: &quot;echo&quot;,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;params&quot;: [ &quot;Hello World!&quot; ],</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>where:</p>
<ul>
<li><code>method</code> is a string with the name of the method to be invoked.</li>
<li><code>params</code> is an array of objects to be passed as parameters to the defined method.</li>
<li><code>id</code> is a value of any type, which is used to match the response with the request that it is replying to.</li>
</ul>
<p>A response message has a <code>result</code> field, an <code>error</code> field, and an <code>id</code>:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;result&quot;: &quot;Welcome!&quot;,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;error&quot;: null,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>where:</p>
<ul>
<li><code>result</code> is the data returned by the invoked method. If an error occurred while invoking the method, this value must be null.</li>
<li><code>error</code> is a specified error code if there was an error invoking the method, otherwise null.</li>
<li><code>id</code> is the id of the request it is responding to.</li>
</ul>
<p>The <a href="http://www.jsonrpc.org/specification">JSON-RPC 2.0 specification</a> makes all 1.0 fields REQUIRED, except for <code>error</code> which MUST NOT be present if there was no error triggered during invocation. The 2.0 specification adds a <code>jsonrpc</code> field in the request message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;jsonrpc&quot;: 2.0,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;method&quot;: &quot;echo&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;params&quot;: [ &quot;Hello World!&quot; ],</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00006"></a><span class="lineno">    6</span>&#160;}</div></div><!-- fragment --> </div><p>and also adds the <code>jsonrpc</code> field to the response message:</p>
<div class="alt"> <div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno">    1</span>&#160;{</div><div class="line"><a name="l00002"></a><span class="lineno">    2</span>&#160;  &quot;jsonrpc&quot;: 2.0,</div><div class="line"><a name="l00003"></a><span class="lineno">    3</span>&#160;  &quot;result&quot;: &quot;Welcome!&quot;,</div><div class="line"><a name="l00004"></a><span class="lineno">    4</span>&#160;  &quot;id&quot;: 1</div><div class="line"><a name="l00005"></a><span class="lineno">    5</span>&#160;}</div></div><!-- fragment --> </div><p>The C operations are straightforward to conform to the JSON-RPC 1.0 or 2.0 specifications. The example JSON-RPC 2.0 request message shown above is created by the following code that uses <code><a class="el" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call()</a></code> to invoke a JSON-RPC service:</p>
<div class="fragment"><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *endpoint = <span class="stringliteral">&quot;http://...&quot;</span>;</div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"></div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *req = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *res = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *args;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#af038763a0eab127fd25993c37a1ea1af">double_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(req, <span class="stringliteral">&quot;jsonrpc&quot;</span>)) = 2.0;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(req, <span class="stringliteral">&quot;method&quot;</span>))  = <span class="stringliteral">&quot;echo&quot;</span>;</div><div class="line">args = <a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(<a class="code" href="structvalue.html#a9d8bdea6bebd0043f1ff58b9a8a38d7c">ref</a>, <span class="stringliteral">&quot;params&quot;</span>);</div><div class="line">*<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(<a class="code" href="xml-rpc_8h.html#ae4c5b08c29e341e61062389633c64743">nth_value</a>(args, 0))       = <span class="stringliteral">&quot;Hello World!&quot;</span>;</div><div class="line">*<a class="code" href="xml-rpc_8h.html#afe5d1d28793b726a082d5f25c6876612">int_of</a>(<a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(req, <span class="stringliteral">&quot;id&quot;</span>))         = 1;</div><div class="line"></div><div class="line"><span class="keywordflow">if</span> (<a class="code" href="json_8h.html#af2e35bee99cf7ceec6bc2d245ecb0112">json_call</a>(ctx, endpoint, req, res))              <span class="comment">// JSON-RPC call</span></div><div class="line">  soap_printf_fault(ctx, stderr);</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#af2855dca8d5186e4eef15f1e30a29916">nth_at</a>(res, <span class="stringliteral">&quot;error&quot;</span>) &gt;= 0)                  <span class="comment">// JSON-RPC error?</span></div><div class="line">  <a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, <a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(res, <span class="stringliteral">&quot;error&quot;</span>));</div><div class="line"><span class="keywordflow">else</span> <span class="keywordflow">if</span> ((<span class="keywordtype">int</span>)res[<span class="stringliteral">&quot;id&quot;</span>] != 1)                        <span class="comment">// matching id field?</span></div><div class="line">  printf(<span class="stringliteral">&quot;response id != request id\n&quot;</span>);</div><div class="line"><span class="keywordflow">else</span>                                                 <span class="comment">// all OK!</span></div><div class="line">  <a class="code" href="json_8h.html#ae0b41e1415944a28b8ef92dc98be8c50">json_write</a>(ctx, <a class="code" href="xml-rpc_8h.html#ae5b4dd82782cd6a663fa4fd19ac9697c">value_at</a>(res, <span class="stringliteral">&quot;result&quot;</span>));          <span class="comment">// display result</span></div></div><!-- fragment --><p>For HTTPS use an https endpoint URL. You can control the HTTPS context as explained in the <a href="http://www.genivia.com/tutorials.html">tutorials.</a></p>
<p>The server-side creates response messages similar to the example shown above. To implement a C JSON-RPC and JSON REST server, please see the example <code>json-currentTimeServer.c</code> located in <code>gsoap/samples/xml-rpc-json</code> in the gSOAP package.</p>
<h2><a class="anchor" id="c-raw"></a>
Embedding and serializing raw JSON data as a JSON value in C            </h2>
<p>A JSON value represented by a <code>value</code> may contain raw JSON data as a string to serialize literally in the output. Deserializing JSON into a JSON <code>value</code> never populates this string, so this feature is to augment JSON output with embedded raw JSON data only.</p>
<p>To add raw JSON data create a <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a></code> structure and assign it to a <code>value</code>:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line"></div><div class="line"><span class="comment">/* create a blob of raw data */</span></div><div class="line"><span class="keyword">struct </span><a class="code" href="struct__rawdata.html">_rawdata</a> *blob = <a class="code" href="xml-rpc_8h.html#a8e941f85f33b0db7b53c1dd5cb292b8c">rawdata_of</a>(v);</div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span> *data = <span class="stringliteral">&quot;[ true, 123, { \&quot;key\&quot;: 456 } ]&quot;</span>;</div><div class="line">blob-&gt;<a class="code" href="struct__rawdata.html#a7564308717e877d133742f96562038eb">__ptr</a> = (<span class="keywordtype">void</span>*)data;</div><div class="line">blob-&gt;<a class="code" href="struct__rawdata.html#a1ae8d382afe249ac3124e9774fac7d96">__size</a> = strlen(data);</div></div><!-- fragment --><p>The <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a> blob</code> can be assigned anywhere where a <code>value</code> is expected, i.e. as an item of an array or as a value property of a JSON object.</p>
<p>To check that a <code>value</code> contains a <code><a class="el" href="struct__rawdata.html" title="Represents the &lt;rawdata&gt; binary data element. ">_rawdata</a></code> value and to retrieve it as raw data:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="json_8h.html">json.h</a>&quot;</span></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line"><span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *v = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">...</div><div class="line">if (<a class="code" href="xml-rpc_8h.html#a5f6e1623bfceefdcafd9c7fbd3371886">is_rawdata</a>(v))</div><div class="line">{</div><div class="line">  <span class="keyword">struct </span><a class="code" href="struct__rawdata.html">_rawdata</a> *blob = <a class="code" href="xml-rpc_8h.html#a8e941f85f33b0db7b53c1dd5cb292b8c">rawdata_of</a>(v);</div><div class="line">  <span class="keywordtype">char</span> *data = (<span class="keywordtype">char</span>*)blob.<a class="code" href="struct__rawdata.html#a7564308717e877d133742f96562038eb">__ptr</a>;</div><div class="line">  <span class="keywordtype">size_t</span> size = blob.<a class="code" href="struct__rawdata.html#a1ae8d382afe249ac3124e9774fac7d96">__size</a>;</div><div class="line">  ...</div><div class="line">}</div></div><!-- fragment --><h1><a class="anchor" id="misc"></a>
Miscellaneous                                                            </h1>
<h2><a class="anchor" id="json-cc"></a>
Compiling XML-RPC/JSON together with gSOAP SOAP services and XML      </h2>
<p>To use JSON (and XML-RPC) with other gSOAP XML data binding code requires a few simple steps to ensure that your project compiles cleanly.</p>
<p>For C++, arguably the best option is to <a class="el" href="index.html#json-ns">Moving JSON types and operations into a C++ namespace </a>.</p>
<p>We present three methods that you can follow. These methods follow different strategies to compile a combined set of files with JSON (and XML-RPC) types and operations with other files with XML data binding types and operations:</p>
<h3>Method 1: #import "xml-rpc.h"</h3>
<p>Before processing a gSOAP XML data binding header file with soapcpp2, add <code>#import "xml-rpc.h"</code> to this header file to include XML-RPC and JSON data types. Then compile the generated files as usual together with <code>jcon.c</code> (or <code>json.cpp</code> for C++) and <code>xml-rpc.c</code> (or <code>xml-rpc.cpp</code> for C++). Also <code>#include "json.h"</code> in your code to use the JSON API.</p>
<p>This is the simplest method. When using wsdl2h, you can automate this method by adding the following three lines to <code>typemap.dat</code>: </p><pre class="fragment">[
#import "xml-rpc.h"
]
</pre><p>This automatically imports the JSON/XML-RPC types and operations into the XML data binding code. You will still need to compile your code together with <code>jcon.c</code> (or <code>json.cpp</code> for C++) and <code>xml-rpc.c</code> (or <code>xml-rpc.cpp</code> for C++).</p>
<h3>Method 2: soapcpp2 -qjson (works with C++ only)</h3>
<p>Use soapcpp2 option <code>-qjson</code> to generate and compile the JSON (and XML-RPC) API code to combine with your other XML data binding code generated with soapcpp2: </p><pre class="fragment">soapcpp2 -qjson -CSL xml-rpc.h
</pre><p>This generates <code>jsonStub.h</code>, <code>jsonH.h</code>, and <code>jsonC.cpp</code>.</p>
<p>Compile the files <code>jsonC.cpp</code>, <code>xml-rpc.cpp</code>, and <code>json.cpp</code> with option <code>-DJSON_NAMESPACE</code> and your other source code files, such as those generated by soapcpp2 for your other .h file: </p><pre class="fragment">c++ -DJSON_NAMESPACE json.cpp jsonC.cpp xml-rpc.cpp ...
</pre><p>Make sure to use <code>#include "json.h"</code> in your code.</p>
<p>The JSON C++ API is in the <code>json</code> C++ namespace. See also <a class="el" href="index.html#json-ns">Moving JSON types and operations into a C++ namespace </a>.</p>
<h3>Method 3: soapcpp2 -pjson</h3>
<p>Use soapcpp2 option <code>-pjson</code> to generate and compile the JSON (and XML-RPC) API code to combine with your other XML data binding code generated with soapcpp2: </p><pre class="fragment">soapcpp2 -c -pjson -CSL xml-rpc.h
</pre><p>This generates <code>jsonStub.h</code>, <code>jsonH.h</code>, and <code>jsonC.c</code>.</p>
<p>Compile the files <code>jsonC.c</code>, <code>xml-rpc.c</code>, and <code>json.c</code> with option <code>-DJSON_NAMESPACE</code> and your other source code files, such as <code>soapClientLib.c</code> generated by soapcpp2 with option <code>-C</code> for your other .h file: </p><pre class="fragment">cc -DJSON_NAMESPACE json.c jsonC.c xml-rpc.c soapClientLib.c stdsoap2.c ...
</pre><p>or the <code>soapServerLib.c</code> file generated by soapcpp2 with option <code>-S</code>: </p><pre class="fragment">cc -DJSON_NAMESPACE json.c jsonC.c xml-rpc.c soapServerLib.c stdsoap2.c ...
</pre><p>Make sure to use <code>#include "json.h"</code> in your code.</p>
<p>This method also works in C++, but it is recommended to use the second method for C++ applications.</p>
<h2><a class="anchor" id="soap"></a>
Serving JSON and SOAP requests on the same server port                   </h2>
<p>SOAP requests are served using the usual <code>soap_serve()</code> call generated by soapcpp2 given an interface header file with SOAP/XML Web service definitions.</p>
<p>We can also serve JSON requests on the same port by using the gSOAP HTTP POST plugin. This plugin serves non-SOAP requests when <code>soap_serve()</code> is called by capturing the HTTP content type of the request and also handles PUT, PATCH and DELETE requests. The httpget plugin is located in <code>gsoap/plugin/httppost.h</code> and <code>gsoap/plugin/httppost.c</code>.</p>
<p>The plugin captures POST requests that have a content type matching a content type entry specified in a table of POST, PUT, PATCH and DELETE handlers. Each entry in this table specifies a content type of a POST request with the function to invoke that will handle it. We can also specify generic POST, PUT, PATCH and DELETE request handlers in this table:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>http_post_handlers my_handlers[] = {</div><div class="line">  { <span class="stringliteral">&quot;application/json&quot;</span>,   json_handler },</div><div class="line">  { <span class="stringliteral">&quot;application/json;*&quot;</span>, json_handler },</div><div class="line">  { <span class="stringliteral">&quot;POST&quot;</span>,               generic_POST_handler },</div><div class="line">  { <span class="stringliteral">&quot;PUT&quot;</span>,                generic_PUT_handler },</div><div class="line">  { <span class="stringliteral">&quot;PATCH&quot;</span>,              generic_PATCH_handler },</div><div class="line">  { <span class="stringliteral">&quot;DELETE&quot;</span>,             generic_DELETE_handler },</div><div class="line">  { NULL }</div><div class="line">};</div></div><!-- fragment --><p>Note that <code>*</code> can be used as a wildcard, in this case we use <code>*</code> to also capture <code>"application/json; charset=utf-8"</code> content type variations.</p>
<p>To register the plugin:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;plugin/httppost.h&quot;</span></div><div class="line"></div><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new();</div><div class="line">soap_register_plugin_arg(ctx, http_post, my_handlers);</div><div class="line">...</div><div class="line">soap_serve(ctx); <span class="comment">// serve SOAP and other POST/PUT/PATCH/DELETE requests</span></div><div class="line">...</div></div><!-- fragment --><p>The handlers in the example <code>my_handlers</code> table given above are used by the plugin to dispatch the request. If a non-SOAP or non-POST request is made, the handler in the table that matches the HTTP content type of the request is invoked. Also generic POST, PUT, PATCH and DELETE handlers can be optionally specified.</p>
<p>A handler in the <code>my_handlers</code> table is a function that takes the context and returns <code>SOAP_OK</code> or an error code. Here is an example <code>json_handler</code> in C:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> json_handler(<span class="keyword">struct</span> soap *ctx)</div><div class="line">{</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *response = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keywordflow">if</span> (<a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request) || soap_end_recv(ctx))</div><div class="line">    <span class="keywordflow">return</span> <a class="code" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01">json_send_fault</a>(ctx); <span class="comment">// return a JSON-formatted fault</span></div><div class="line">  ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">  ... <span class="comment">// set the &#39;response&#39; value</span></div><div class="line">  <span class="comment">// set http content type</span></div><div class="line">  ctx-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line">  <span class="comment">// send http header 200 OK and JSON response</span></div><div class="line">  <span class="keywordflow">if</span> (soap_response(ctx, SOAP_FILE)</div><div class="line">   || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(ctx, response)</div><div class="line">   || soap_end_send(ctx))</div><div class="line">    soap_closesock(ctx);</div><div class="line">  <span class="keywordflow">return</span> SOAP_OK;</div><div class="line">}</div></div><!-- fragment --><p>Note that we use <code><a class="el" href="json_8h.html#a6aa4b933cac792280e0a7844d346cf01" title="Respond with a JSON error when an internal fault occurred (i.e. soap-&gt;error is nonzero), as per Google JSON Style Guide. ">json_send_fault()</a></code> instead of <code>soap_send_fault()</code> when an internal error occurred, since we want the error to be reported in JSON format as per Google JSON Style Guide. For application-specific errors, we use <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> as follows:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (some application error occurred)</div><div class="line">  <a class="code" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0">json_send_error</a>(ctx, 400, <span class="stringliteral">&quot;Error message&quot;</span>, <span class="stringliteral">&quot;Error details&quot;</span>);</div><div class="line"><span class="keywordflow">else</span></div><div class="line">  ... <span class="comment">// send the response</span></div></div><!-- fragment --><p>You can specify an HTTP error code such as 400 in this case, which means that a HTTP 400 Bad Request is returned to the client.</p>
<p>The <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> function is a convenient shortcut to return an error message with an HTTP error code. To return a JSON response with a HTTP error code use the following:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> status = 400; <span class="comment">// HTTP 400 Bad Request</span></div><div class="line"><a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>-&gt;http_content = <span class="stringliteral">&quot;application/json; charset=utf-8&quot;</span>;</div><div class="line"><span class="keywordflow">if</span> (soap_response(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>, SOAP_FILE + status)</div><div class="line"> || <a class="code" href="json_8h.html#a9c7efe04167da2598017b8734bc4a527">json_send</a>(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>, v)</div><div class="line"> || soap_end_send(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>))</div><div class="line">  soap_closesock(<a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a>);</div></div><!-- fragment --><p>A <code>generic_POST_handler</code> should be similar to the above. The HTTP content type of the request is stored in the <code>http_content</code> string variable of the context.</p>
<p>A <code>generic_PUT_handler</code> and <code>generic_PATCH_handler</code> should not return a response message but should call <code>soap_send_empty_response()</code> instead. Likewise, these handlers should return a HTTP status code instead of calling <code><a class="el" href="json_8h.html#a7e7cde2a9cf69f2ba6a16049c95225a0" title="Send JSON error back to the client using the specified HTTP status code and a message and details...">json_send_error()</a></code> since the HTTP body should be empty:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> generic_PUT_handler(<span class="keyword">struct</span> <a class="code" href="structvalue.html#a874a72d34f39c0839bc53ccb5f9d1e99">soap</a> *ctx)</div><div class="line">{</div><div class="line">  <span class="keyword">struct </span><a class="code" href="structvalue.html">value</a> *request = <a class="code" href="xml-rpc_8h.html#a432d985b787e5ae321a57064408b4909">new_value</a>(ctx);</div><div class="line">  <span class="keywordflow">if</span> (!ctx-&gt;http_content || soap_tag_cmp(ctx-&gt;http_content, <span class="stringliteral">&quot;application/json*&quot;</span>))</div><div class="line">  {</div><div class="line">    <span class="keywordflow">return</span> 400; <span class="comment">// HTTP Bad Request</span></div><div class="line">  }</div><div class="line">  <span class="keywordflow">if</span> (<a class="code" href="json_8h.html#a328f12bad425de77a0df4e31471bb1c2">json_recv</a>(ctx, request) || soap_end_recv(ctx))</div><div class="line">    <span class="keywordflow">return</span> 400; <span class="comment">// HTTP Bad Request</span></div><div class="line">  ... <span class="comment">// use the &#39;request&#39; value</span></div><div class="line">  <span class="comment">// send http header 200 OK and empty http body</span></div><div class="line">  <span class="keywordflow">return</span> soap_send_empty_response(ctx);</div><div class="line">}</div></div><!-- fragment --><p>The <code>soap_tag_cmp()</code> function is similar to <code>strcmp()</code> but it is case insensitive and supports <code>*</code> (any number of characters) and <code>-</code> (any single character) wildcards.</p>
<p>To compile your server application that serves JSON and SOAP requests, see <a class="el" href="index.html#json-cc">Compiling XML-RPC/JSON together with gSOAP SOAP services and XML </a>.</p>
<h2><a class="anchor" id="fp"></a>
Floating point format                                                      </h2>
<p>The floating point format used to output values in XML-RPC and JSON is by default ".17lG' to ensure accuracy up to the last digit. The format can be set as follows:</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>soap *ctx = soap_new1(SOAP_C_UTFSTRING | SOAP_XML_INDENT);</div><div class="line">ctx-&gt;double_format = <span class="stringliteral">&quot;%lG&quot;</span>;</div></div><!-- fragment --><h2><a class="anchor" id="base64"></a>
JSON and base64                                                        </h2>
<p>JSON has no binary type to transmit binary data. Sending binary data in JSON strings as text is not recommended, due to NULs and problems with Unicode/UTF-8 sequences.</p>
<p>Base64 is a common encoding format for binary data. A JSON string with base64 content is our recommended option.</p>
<p>To populate JSON data with base64-encoded binary content, you can simply create and assign a <code><a class="el" href="struct__base64.html" title="Represents the &lt;base64&gt; binary data element. ">_base64</a></code> value as described earlier (e.g. by casting a <code><a class="el" href="struct__base64.html" title="Represents the &lt;base64&gt; binary data element. ">_base64</a></code> structure to a value in C++). Receiving base64-encoded content with JSON is not possible, because the necessary type information is lost in transit. The base64 content will arrive at the receiver simply as a string with base64 content.</p>
<p>You can explicitly decode the base64 string back to binary as shown here for C++:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (v.<a class="code" href="structvalue.html#a9b7b0789dc59f7a50c009c487777c282">is_string</a>())</div><div class="line">{</div><div class="line">  <span class="comment">/* assuming base64 content in string value v, decoded it */</span></div><div class="line">  <span class="keywordtype">int</span> len;</div><div class="line">  <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *ptr = (<span class="keywordtype">unsigned</span> <span class="keywordtype">char</span>*)soap_base642s(ctx, (<span class="keyword">const</span> <span class="keywordtype">char</span>*)v, NULL, 0, &amp;len);</div><div class="line">  <span class="comment">/* ptr points to binary of length len or is NULL when decoding failed */</span></div><div class="line">  <span class="keywordflow">if</span> (ptr)</div><div class="line">    ... <span class="comment">// success</span></div><div class="line">  ctx-&gt;error = SOAP_OK; <span class="comment">// fail and reset error</span></div></div><!-- fragment --><p>And for C:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(v))</div><div class="line">{</div><div class="line">  <span class="comment">/* assuming base64 content in string value v, decoded it */</span></div><div class="line">  <span class="keywordtype">int</span> len;</div><div class="line">  <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> *ptr = (<span class="keywordtype">unsigned</span> <span class="keywordtype">char</span>*)soap_base642s(ctx, *<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(v), NULL, 0, &amp;len);</div><div class="line">  <span class="comment">/* ptr points to binary of length len or is NULL when decoding failed */</span></div><div class="line">  <span class="keywordflow">if</span> (ptr)</div><div class="line">    ... <span class="comment">// success</span></div><div class="line">  ctx-&gt;error = SOAP_OK; <span class="comment">// fail and reset error</span></div></div><!-- fragment --><h2><a class="anchor" id="dateTime"></a>
JSON and ISO 8601 dateTime                                           </h2>
<p>To populate JSON data with ISO 8601 date time content, you can simply assign a <code>ULONG64</code> value cast from a <code>time_t</code> value as described earlier. Receiving ISO 8601 date time content with JSON is not possible, because the necessary type information is lost in transit. The content will arrive at the receiver simply as a string with a date and time.</p>
<p>You can explicitly convert a string with an ISO 8601 date time to a <code>time_t</code> value as shown here for C++:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (v.<a class="code" href="structvalue.html#a9b7b0789dc59f7a50c009c487777c282">is_string</a>())</div><div class="line">{</div><div class="line">  time_t tm;</div><div class="line">  <span class="keywordflow">if</span> (soap_s2dateTime(ctx, (<span class="keyword">const</span> <span class="keywordtype">char</span>*)v, &amp;tm) == SOAP_OK)</div><div class="line">    ... <span class="comment">// success</span></div></div><!-- fragment --><p>And for C:</p>
<div class="fragment"><div class="line"><span class="keywordflow">if</span> (<a class="code" href="xml-rpc_8h.html#a243e9ce66455d2d5819e0db13ae0c104">is_string</a>(v))</div><div class="line">{</div><div class="line">  time_t tm;</div><div class="line">  <span class="keywordflow">if</span> (soap_s2dateTime(ctx, *<a class="code" href="xml-rpc_8h.html#acae47cb0609e5d6ae32e6ceb75f85b16">string_of</a>(v), &amp;tm) == SOAP_OK)</div><div class="line">    ... <span class="comment">// success</span></div></div><!-- fragment --><p>The disable UTC time zone <code>Z</code> in the dateTime string, use <code>-DWITH_NOZONE</code> to compile <code>stdsoap2.c</code> (for C) or <code>stdsoap2.cpp</code> (for C++).</p>
<h2><a class="anchor" id="issues"></a>
Potential issues                                                       </h2>
<p>The JSON parser follows the published JSON "standards" but is a bit more forgiving, meaning that it parses the following extensions:</p>
<ul>
<li>The parser admits floating point values that are formatted as C floating point values in addition to JSON formats for numbers (which are more restrictive).</li>
<li>The parser admits <code>NaN</code>, <code>+Inf</code>, <code>-Inf</code> as floating point values.</li>
<li>The parser admits hexadecimal integer values of the form <code>0xHHHH</code>.</li>
<li>Any additional trailing content after a valid JSON object or array is silently ignored.</li>
<li>To parse JSON data from files or from any other non-HTTP source use the <code>SOAP_ENC_PLAIN</code> flag to initialize the context, otherwise files containing just the JSON values <code>true</code>, <code>false</code>, and <code>null</code> are not parsed.</li>
</ul>
<h1><a class="anchor" id="copyright"></a>
Copyright                                                           </h1>
<p>Copyright (c) 2017, Robert van Engelen, Genivia Inc. All rights reserved. </p>
</div></div><!-- contents -->
<hr class="footer">
<address class="footer">
Copyright (C) 2020, Robert van Engelen, Genivia Inc., All Rights Reserved.
</address>
<address class="footer"><small>
Converted on Fri Oct 16 2020 16:44:40 by <a target="_blank" href="http://www.doxygen.org/index.html">Doxygen</a> 1.8.11</small></address>
<br>
<div style="height: 246px; background: #DBDBDB;">
</body>
</html>
